Day 52 of 1022. Sum of Root To Leaf Binary Numbers Today’s problem was a great mix of binary representation + tree traversal. Each root-to-leaf path in the binary tree forms a binary number, and the goal is to compute the sum of all those numbers efficiently. Key Insight: Instead of storing the entire path, we can build the number on the go using: ➡️ current = (current << 1) | node.val This is equivalent to: Left shift → multiply by 2 Add current bit Reached a leaf node? That means we formed one complete binary number → add it to the result. 🌱 What I practiced today: ✔ Depth First Search (DFS) ✔ Bit Manipulation in Trees ✔ Writing clean recursive logic ✔ Optimizing space by avoiding extra storage ⏱ Time Complexity: O(n) 📦 Space Complexity: O(h) – recursion stack ✨ This problem is a perfect example of how combining concepts (Trees + Bits) leads to elegant solutions. Consistency is the real key 🔑 — learning something new every single day! #Day52 LeetCode BinaryTree DSA Journey Coding JavaScript Notes #Python #ProblemSolving TechGrowth
Binary Tree Sum of Root to Leaf Paths
More Relevant Posts
-
🧩 How Do YOU Solve This ❓ ❓ ❓ 👉 You must find the smallest missing positive integer in an unsorted array. 👉 Your Time Complexity must be O(n) and your Space Complexity O(1). 👉 No sorting allowed, no hash maps. Before coding, YOU must understand these key insights: 1️⃣ For an array of size n, the answer is always between 1 and n+1. This is crucial! 2️⃣ Use the array itself as storage: Since we know valid numbers are only 1 to n, we can use array indices as a "hash". Position 0 represents number 1, position 1 represents number 2, and so on. e.g: [1, 2, 3, 4, 5] => positions are: [0, 1, 2, 3, 4] 3️⃣ Clean before processing: Replace all invalid numbers (≤ 0 or > n) with n+1. They can't be the answer anyway. 4️⃣ Swap into place: Use a while loop to keep swapping each number to its correct position (number k goes to index k-1) until everything that can be placed is placed. 5️⃣ Scan through and return the first index where the expected number is missing. 💡 Making sure the while loop doesn't become O(n²). It stays O(n) because each number gets swapped at most once to its final position across the entire algorithm. #Python #AlgorithmPractice #ProblemSolving #CodingChallenge #DataStructures
To view or add a comment, sign in
-
-
🚀 DSA Day — Merge Two Sorted Arrays (LeetCode 88) Today I worked on a classic problem that looks simple but teaches an important optimization technique 👇 🔹 Problem Statement You are given two sorted arrays and need to merge them into one sorted array in-place. Example: nums1 = [1, 7, 8, 0, 0, 0], m = 3 nums2 = [2, 5, 6], n = 3 ✅ Output: [1, 2, 5, 6, 7, 8] 🔸 Approach 1: Brute Force ✔ Copy nums2 into nums1 ✔ Sort the entire array ⏱ Time Complexity: O((m+n) log(m+n)) 👉 Simple but not efficient 🔸 Approach 2: Optimized (Two Pointers) 💡 Key Idea: Start filling from the end ✔ Compare last elements of both arrays ✔ Place the larger one at the end ✔ Move pointers accordingly ⏱ Time Complexity: O(m+n) 📦 Space Complexity: O(1) 🔥 Why this works? Because nums1 already has extra space at the end — we use it smartly without shifting elements. 💻 Code Snippet (Optimized) https://lnkd.in/g9Z7yf3d def merge(nums1, m, nums2, n): i = m - 1 j = n - 1 k = m + n - 1 while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 while j >= 0: nums1[k] = nums2[j] j -= 1 k -= 1 🎯 Key Takeaway 👉 Always think from the end when dealing with in-place array problems. #DSA #Python #CodingInterview #LeetCode #ProblemSolving #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
🚀 LeetCode 41 – First Missing Positive (Hard) Solved the classic First Missing Positive problem using two different approaches. 🧩 Problem: Given an unsorted integer array, find the smallest missing positive integer in O(n) time and O(1) space. 🔗 Try the problem here:https://lnkd.in/gCAGSftq Approach 1: Using Hash Set 💡 Idea: Store all elements in a set and check from 1 upward to find the first missing number. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(n) ❌ (extra space used) 🔎 Why Not Optimal? Uses extra memory, so it doesn’t satisfy the O(1) space requirement. Approach 2: Cyclic Sort (Optimal Solution) 💡 Idea: Place each number x at index x - 1 if 1 ≤ x ≤ n. Then scan the array to find the first index where nums[i] != i+1. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) ✅ 🔥 Why This Works? We use the array itself as a hash map by placing numbers in their correct indices. Each element is swapped at most once → overall linear time. If you're preparing for interviews, this is a must-know hard-level pattern 💪 #LeetCode #Coding #DataStructures #Algorithms #DSA #Python #CodingInterview #InterviewPreparation #ProblemSolving #SoftwareDeveloper #100DaysOfCode #TechCareers #ProgrammersLife #CodeNewbie #CompetitiveProgramming
To view or add a comment, sign in
-
-
🚀 Day 6: Decoding Maximum Consecutive One's 💡 How I solved it: *Maintained a running counter that increments every time I encounter a 1. *Used a global maximum variable to capture the highest streak reached before hitting a 0. *The Reset: Every time a 0 appeared, I reset the current counter to zero to begin tracking the next potential streak. 🧠 Key Takeaway: *Efficiency: Achieved O(n) time complexity and O(1) space—optimal for large datasets. *State Tracking: Learned the importance of maintaining a "local" vs. "global" state. It’s a foundational logic used in many sliding window and greedy algorithm problems. One step closer to mastering Data Structures and Algorithms! 💻🔥 The logic is getting sharper every day! 📈🤝 #100DaysOfCode #DSA #Python #ProblemSolving #StriverA2ZSheet #CodingJourney
To view or add a comment, sign in
-
-
Today’s random problem was 1743. Restore the Array From Adjacent Pairs. The question asks us to reconstruct an original array given only the adjacent pairs. We know the array has no duplicates and every adjacent pair is unique. Key Insight: 1. The endpoints (first and last elements) will only have one neighbor. 2. All middle elements will have exactly two neighbors. 3. To restore the array, we just need to find one of those "endpoints" and follow the trail! Problem Is Tricky because of Traversal: 1. Finding the Start: We build an graph and look for a node with a degree of 1. If we started in the middle, we’d have to go in two directions, which makes the logic hard. 2. Avoiding Infinite Loops: Since the graph is undirected, when moving from node A to node B, node B will list A as a neighbor. We must pass a prev reference to ensure we don't bounce back and forth between the same two numbers. My Approach: I used a DFS starting from an endpoint. By keeping track of the prev node, we can traverse the entire path linearly until we hit the other endpoint. Complexity: Time: O(n) Space: O(n) #LeetCode #CodingChallenge #SoftwareEngineering #PythonProgramming #DataStructures #Algorithms #GraphTheory #DFS #ProblemSolving #TechInterviewPrep #Python #Java
To view or add a comment, sign in
-
-
Topic 5/100 🚀 🧠 Topic 5 — Iterators Ever wondered how a for loop actually works behind the scenes? 🤔 This is the concept powering it. 👉 What is it? Iterators are objects that allow you to traverse through data step-by-step using __iter__() and __next__() methods. 👉 Use Case: Used in real-world applications for: Custom data pipelines Streaming data Building your own iterable objects 👉 Why it’s Helpful: Gives full control over iteration Enables custom looping logic Foundation for generators 💻 Example: class Counter: def __init__(self, max): self.max = max self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.max: self.current += 1 return self.current raise StopIteration for num in Counter(3): print(num) 🧠 What’s happening here? We created a custom object that behaves like a loop by controlling how values are returned one by one. ⚡ Pro Tip: If you understand iterators, you’ll unlock how Python handles loops internally. 💬 Follow this series for more Topics #Python #BackendDevelopment #100TopicOfCode #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
-
Just solved LeetCode 862: Shortest Subarray with Sum at Least K If you've ever been trapped by a sliding window that just won't slide right, this one is for you! 👇 The Brute Force (O(N²)) The most intuitive approach is to calculate the prefix sum of the array, and then use a nested loop to check the sum of every possible subarray, keeping track of the shortest one that is >= K. The problem? The array length can be up to 10⁵. An O(N²) solution will immediately hit a Time Limit Exceeded (TLE). We need O(N). Normally, to find a shortest/longest subarray, we reach for the Sliding Window technique. But there's a catch: The array contains negative numbers. Because of negative numbers, our prefix sum is NOT monotonically increasing. The standard sliding window is completely broken here. To fix this, we need a way to track prefix sums intelligently. We can use a Double-Ended Queue (Deque) to store tuples of (prefix_sum, index) and force it to be strictly increasing (monotonic). Shrinking the window: As we iterate, we check if current_sum - smallest_prefix_sum_in_deque >= K. If it is, we found a valid subarray! We record the length, and throw away that starting index (pop left). Why? Because any future subarray using that start index would only be longer and therefore worse. Maintaining Monotonicity (Pop Right): What if our current_sum dips and is smaller than the most recent prefix sums in our deque? We can keep popping the back of queue as the older greater prefix sums work but make the subarray longer. This approach has a time complexity of O(n) and a space complexity of O(n) as well as in the worst case, the queue may contain n prefix sum where n: number of elements in the array. #LeetCode #Python #Algorithms #DataStructures #SoftwareEngineering #ProblemSolving #CodingInterviews
To view or add a comment, sign in
-
-
✅ Day 69 of 100 Days LeetCode Challenge Problem: 🔹 #1009 – Complement of Base 10 Integer 🔗 https://lnkd.in/geVPugvi Learning Journey: 🔹 Today’s challenge involved finding the bitwise complement of a base-10 integer. 🔹 I first converted the integer into its binary representation using bin(n)[2:] to remove the 0b prefix. 🔹 Then I iterated through each bit and flipped it: • 0 becomes 1 • 1 becomes 0 🔹 After constructing the flipped binary string, I converted it back to a decimal integer using int(s, 2). Concepts Used: 🔹 Binary Representation 🔹 Bit Manipulation 🔹 String Traversal 🔹 Base Conversion (Binary → Decimal) Key Insight: 🔹 Converting the number to binary makes it easy to flip bits directly. 🔹 After inversion, converting the binary string back to base-10 produces the required complement. Complexity: 🔹 Time: O(b) where b is the number of bits in n 🔹 Space: O(b) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
-
✅ First Unique Character in a String | Hash Map | LeetCode Solved the First Unique Character in a String problem using a frequency dictionary approach. 💡 Problem Given a string s, return the index of the first non-repeating character. If it does not exist, return -1. ⚡ Approach — Hash Map • Traverse the string and store character frequencies in a dictionary. • Iterate through the dictionary to find the character with frequency 1. • Return its index using s.index(char). ⏱ Complexity • Time: O(n) • Space: O(1) (since character set is limited) 🧠 Key Learning Frequency counting is a powerful technique for string problems. Hash maps help reduce nested loops and improve efficiency. Small string problems like this build a strong foundation for advanced DSA concepts. #LeetCode #DSA #Python #HashMap #StringProblems #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
✅ Day 74 of 100 Days LeetCode Challenge Problem: 🔹 #653 – Two Sum IV: Input is a BST 🔗 https://lnkd.in/g9vDFKMA Learning Journey: 🔹 Today’s problem required checking whether there exist two nodes in a Binary Search Tree whose values sum to k. 🔹 I performed a Depth-First Search (DFS) traversal using a stack to visit all nodes of the tree. 🔹 While traversing, I stored each node’s value in a list. 🔹 Then I used a hash set to track visited values and checked whether the complement (k - value) already exists. 🔹 If the complement is found, it means two numbers sum to k, so the function returns True. Concepts Used: 🔹 Depth-First Search (DFS) 🔹 Stack-based Tree Traversal 🔹 Hash Set for Fast Lookup 🔹 Two Sum Pattern Key Insight: 🔹 The classic Two Sum approach works well after collecting values from the BST. 🔹 Using a set allows O(1) lookup, making it efficient to check complements during iteration. Complexity: 🔹 Time: O(n) 🔹 Space: O(n) #LeetCode #Algorithms #DataStructures #CodingInterview #100DaysOfCode #SoftwareEngineering #Python #ProblemSolving #LearningInPublic #TechCareers
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development