Day 76 of #100DaysOfCode Today I solved "All Nodes Distance K in Binary Tree" on LeetCode using a DFS + Backtracking approach. Key Idea: We need to find all nodes at distance K from a given target node — not just in its subtree, but also through its ancestors. Approach: • First, locate the target node using DFS • From target → collect nodes in its subtree at distance K • While backtracking: Track distance from current node to target Check if current node is at distance K Explore the opposite subtree for remaining distance This allows us to cover both downward and upward paths in the tree. Concepts Used: • Binary Trees • Depth First Search (DFS) • Backtracking • Tree traversal Time Complexity: O(n) Space Complexity: O(h) This problem really improved my understanding of handling tree paths beyond simple parent-child traversal Every day, a new pattern unlocked. #Day76 #100DaysOfCode #LeetCode #BinaryTree #DFS #Backtracking #Cpp #CodingJourney
Binary Tree Distance K Solution with DFS and Backtracking
More Relevant Posts
-
Day 83 of #100DaysOfCode Today I solved "Binary Tree Maximum Path Sum" on LeetCode using DFS + Recursion. Key Idea: At every node, we calculate the maximum path sum passing through it. But here’s the twist We ignore negative paths because they reduce the total sum. Approach: • Recursively get the max path sum from left and right subtrees • Ignore negative values using max(0, …) • Update the global answer as: root->val + left + right • Return to parent: root->val + max(left, right) This ensures we consider both: Path passing through the node Path extending upwards Concepts Used: • Binary Trees • Depth First Search (DFS) • Recursion • Greedy choice (ignore negative paths) Time Complexity: O(n) Space Complexity: O(h) This problem really sharpened my understanding of handling multiple path possibilities in trees From simple traversals to advanced patterns — growth is visible #Day83 #100DaysOfCode #LeetCode #BinaryTree #DFS #Cpp #CodingJourney
To view or add a comment, sign in
-
-
📅 Day 15 / 100 – #100DaysOfCode Solved Two Sum II – Input Array Is Sorted on LeetCode 💻 Today’s focus was on improving problem-solving by leveraging sorted array properties. 🔍 What I learned: Practiced the HashMap approach (O(n) time, O(n) space) Understood how 1-based indexing works in this problem Realized that since the array is sorted, this can be optimized further using the Two Pointer technique (O(1) space) 🔥 🧠 Key Insight: Don’t just solve the problem — look for constraints (like sorted arrays) to optimize further. ⚡ Next Step: Will implement the Two Pointer approach to achieve constant space complexity. Consistency > Motivation. Let’s keep building 💪 #Day15 #100DaysOfCode #DSA #LeetCode #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
Day 72/150 🚀 LeetCode 104: Maximum Depth of Binary Tree 🧠 Problem Given the root of a binary tree, return its maximum depth. 📌 Example Input → root = [3,9,20,null,null,15,7] Output → 3 💡 Approach • Use recursion (DFS) • Calculate left subtree depth • Calculate right subtree depth • Return max(left, right) + 1 ⏱ Time Complexity O(n) 📦 Space Complexity O(h) ✅ Result: Accepted ⚡ Runtime: 0 ms (Beats 100%) #Day72 #LeetCode #DSA #BinaryTree #Recursion #CodingJourney #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 68 of #100DaysOfCode 🔥 Solved Median of Two Sorted Arrays (LeetCode Q4) today! 💡 Problem Insight: Find the median of two sorted arrays in an efficient way without merging them. 🧠 Approach: - Use Binary Search on the smaller array - Partition both arrays such that left side has smaller elements and right side has larger ones - Ensure correct balance of elements on both sides ⚙️ Algorithm: - Apply binary search to find correct partition - Check conditions for valid split - If valid → calculate median based on total length - Else → adjust search space ⏱️ Complexity: - Time: O(log(min(n, m))) - Space: O(1) 📌 Key Learning: Brute force is not always the answer — smart partitioning can optimize everything. 💬 Think smart, not hard. #DSA #LeetCode #BinarySearch #100DaysOfCode #CodingJourney #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
LeetCode — Day 39 Solved: Binary Tree Paths Today’s problem focused on DFS traversal + path building. Approach: • Use DFS to traverse the tree • Maintain a path string while moving down • When a leaf node is reached → store the path Key insight: This problem is about carrying state (the path) through recursion and knowing exactly when to record it. It’s not just traversal — it’s about building meaningful output during traversal. Good practice for: • Tree recursion • String handling • Understanding leaf conditions #LeetCode #Day39 #DSA #BinaryTrees #DFS #ProblemSolving #Consistency #Cpp #CodingJourney
To view or add a comment, sign in
-
-
Day 93 of #100DaysOfCode Today I solved "Add One Row to Tree" on LeetCode using a DFS approach. Key Idea: We need to insert a new row of nodes at a given depth, while preserving the existing structure below it. Approach: • If depth == 1: Create a new root and attach the original tree as its left child • Otherwise: Traverse the tree using DFS When we reach level depth - 1: Create new nodes with given value Attach original left subtree to new left node Attach original right subtree to new right node Concepts Used: • Binary Trees • Depth First Search (DFS) • Recursion • Tree modification Time Complexity: O(n) Space Complexity: O(h) This problem was a great exercise in modifying tree structure while maintaining connections correctly Not just traversing trees now… actually reshaping them #Day93 #100DaysOfCode #LeetCode #BinaryTree #DFS #Cpp #CodingJourney
To view or add a comment, sign in
-
-
Day 38 Today I solved: Majority Element (LeetCode 169) 💡 Problem: Given an array, find the element that appears more than [n/2] times. You can assume that the majority element always exists. 💡 My Approach: I used a HashMap (frequency counting) approach: 1️⃣ Traverse the array and store frequency of each element 2️⃣ Calculate n/2 3️⃣ Iterate through the map 👉 Return the element whose frequency is greater than n/2 💡 Key Insight: The majority element will always dominate the count (> n/2), so once counted, it’s easy to identify ✅ ⚡ Complexity: Time: O(n) Space: O(n) #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 37 Today I solved: Subarray Sum Equals K (LeetCode 560) 💡 Problem: Given an array and an integer k, find the total number of subarrays whose sum equals k. 💡 My Approach: I used Prefix Sum + HashMap for an optimal solution: 1️⃣ Compute running prefix sum while traversing the array 2️⃣ Use a HashMap to store frequency of prefix sums 3️⃣ At each index, check: 👉 If (currentSum - k) exists in map → we found subarrays 4️⃣ Add its frequency to the count 5️⃣ Update the map with current prefix sum 💡 Key Insight: If prefixSum[j] - prefixSum[i] = k 👉 Then prefixSum[i] = prefixSum[j] - k So instead of checking all subarrays ❌ We use previously seen sums to get result in O(n) ✅ ⚡ Complexity: Time: O(n) Space: O(n) 🔥 Takeaway: Prefix Sum + HashMap is a powerful combo for subarray problems 🚀 #LeetCode #DSA #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
-
Day 3️⃣ /15 — Consistency Challenge 🚀 🔥 Today’s problem: LeetCode 3761 — Minimum Absolute Distance Between Mirror Pairs 🔹 Approach: The goal is to find the minimum index distance between a number and its mirror (reverse) in the array. Using Reverse Function: For each number, compute its reverse (e.g., 123 → 321). HashMap for Tracking: Use a Map<Integer, Integer> to store: key → reversed number value → index where it appeared Traverse the Array: For each index i: Check if nums[i] already exists in the map 👉 This means we have previously seen its mirror If yes, calculate distance: i - previousIndex Update the minimum answer Store Reverse: Insert reverse(nums[i]) into the map with current index Time Complexity: O(n) Space Complexity: HashMap storage → O(n) Small steps. Daily progress. Building consistency. 💯 #LeetCode #DSA #Consistency #CodingJourney #LearnInPublic #DayChallenge
To view or add a comment, sign in
-
-
38 of #100DaysOfCode 💻 Solved LeetCode 560 – Subarray Sum Equals K using an optimized approach ⚡ 🔍 Instead of checking every subarray (O(n²)), I used Prefix Sum + HashMap to bring it down to O(n) 🧠 How it works (Mapping Logic) Keep a running sum → currSum Store frequencies of sums in a map → prefix[currSum] At each step, check: 👉 If (currSum - k) already exists in the map 👉 That means a subarray with sum = k is found ✅ Add its frequency to the count Update the map with current sum 📌 Key Takeaways ✔️ Prefix Sum pattern ✔️ HashMap for constant-time lookup ✔️ Pattern recognition > brute force ✔️ Time Complexity: O(n) #LeetCode #DSA #CodingJourney #Cpp #ProblemSolving #Tech #100DaysOfCode
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