🚀 Day 55/100: LeetCode Challenge – Path Sum (Binary Trees) Halfway through the 100-day journey and the momentum is only building! Today’s focus was on Binary Trees and recursion with the "Path Sum" problem. 💡 The Logic The goal is to determine if a tree has a root-to-leaf path that sums up to a specific targetSum. My approach used a recursive Depth-First Search (DFS): Base Case: If the node is null, return false. Leaf Check: If we reach a leaf node, check if the remaining sum equals the node's value. Recursion: Subtract the current node's value from the target and move down to the left and right children. 📊 Results Runtime: 0 ms (Beats 100.00% of Java users) ⚡ Memory: 44.74 MB (Beats 89.55% of Java users) 🧠 Recursive solutions for trees always feel like magic when they click. It’s all about breaking down a complex structure into the simplest possible sub-problem. Onward to Day 56! #LeetCode #100DaysOfCode #Java #DataStructures #Algorithms #SoftwareEngineering #BinaryTree #CodingChallenge
Path Sum in Binary Trees with Java
More Relevant Posts
-
🔥 Day 36 of #75DaysofLeetCode 🔥 LeetCode 437 – Path Sum III | Prefix Sum + DFS Magic! Struggled with counting paths in a binary tree that sum up to a target? 🤔 This problem looks like a typical tree traversal… but the optimal solution is 🔥 next-level thinking. 💡 Problem Insight: We need to count all paths (not necessarily from root) where the sum equals targetSum. Condition → Path must go downwards (parent → child). 🚫 Brute Force Idea: Start DFS from every node → check all paths ⏱️ Time Complexity: O(n²) (not efficient) ⚡ Optimized Approach: Prefix Sum + HashMap Instead of recomputing sums, we: ✔ Maintain a running sum (currentSum) ✔ Store previous sums in a HashMap ✔ Check if (currentSum - targetSum) exists 👉 This tells us how many valid paths end at the current node! 🧠 Core Logic: Add current node value to currentSum Check: currentSum - targetSum in map Update map before recursion Backtrack after recursion ⏱️ Complexity: Time: O(n) Space: O(n) 🚀 Key Takeaway: Whenever you see: 👉 "subarray sum = k" or 👉 "path sum = target" Think Prefix Sum + HashMap 💡 #LeetCode #DSA #Java #CodingInterview #BinaryTree #Programming #SoftwareEngineering #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 Day 59/100 – LeetCode Challenge 📌 Problem Solved: Remove Duplicates from Sorted Array II (Medium) Today’s problem was a great exercise in in-place array manipulation and two-pointer technique. 💡 Key Idea: Since the array is already sorted, duplicates are adjacent. Instead of removing all duplicates, we allow each element to appear at most twice. 👉 The trick is to compare the current element with the element at index k-2. If they are the same → skip ❌ If different → keep it ✅ ⚙️ Approach: Initialize pointer k = 2 Traverse from index 2 Copy valid elements forward Maintain order without extra space 🧠 What I learned: How to efficiently handle constraints like “at most twice” Importance of thinking in terms of index relationships (k-2) Writing optimal O(n) solutions with O(1) space 📊 Performance: ⚡ Runtime: 0 ms (100%) 💾 Memory: 48.46 MB 💻 Tech Used: Java Consistency is key 🔑 — 59 days done, 41 more to go! #100DaysOfCode #LeetCode #Java #DataStructures #CodingChallenge #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
🚀 Day 546 of #750DaysOfCode🚀 🔥 Solved: Check if Strings Can be Made Equal With Operations I (LeetCode Easy) 💡 Problem Insight We are allowed to swap characters at indices where: 👉 j - i = 2 This means: Index 0 ↔ 2 (even positions) Index 1 ↔ 3 (odd positions) 🚫 But we cannot mix even and odd indices 🧠 Key Observation The string is divided into 2 independent groups: Even indices → (0, 2) Odd indices → (1, 3) 👉 We can rearrange within each group freely 👉 So both groups must match between s1 and s2 ⚡ Approach Extract characters: Even indices from both strings Odd indices from both strings Sort both groups Compare: Even parts must match Odd parts must match 📈 Complexity Time: O(1) Space: O(1) 💬 Key Takeaway Sometimes problems look like string manipulation, but the real trick is: 👉 Understanding constraints → grouping → independent transformations 🔁 Consistency check ✔️ Another day, another step forward 🚀 #LeetCode #DataStructures #Algorithms #Java #CodingChallenge #ProblemSolving #100DaysOfCode #Consistency
To view or add a comment, sign in
-
-
🚀 Day 3/100 – LeetCode Challenge 🔍 Problem: Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be inserted to maintain the sorted order. 💡 Key Concepts Used: • Binary Search • Time Complexity Optimization – O(log n) • Efficient searching in sorted arrays 📚 What I Learned: • How binary search reduces search time significantly compared to linear search • Handling edge cases when the target element is not present • Determining the correct insertion index while maintaining sorted order hashtag #100DaysOfCode #LeetCode #Java #DataStructures #Algorithms #BinarySearch #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
💡 Day 54 of LeetCode Problem Solved! 🔧 🌟 560. Subarray Sum Equals K 🌟 🔗 Solution Code: https://lnkd.in/g5VwiFKd 🧠 Approach: Prefix Sum & Hash Map Store cumulative sums in a Map Check for (current_sum - k) to find matching subarrays in one pass ⚡ Key Learning: Mastering the Prefix Sum + HashMap pattern is a game-changer for transforming $O(n^2)$ subarray problems into efficient $O(n)$ solutions. ⏱️ Complexity: Time: O(n) Space: O(n) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #PrefixSum #DataStructures
To view or add a comment, sign in
-
-
🚀 Day 63 of #100DaysOfLeetCode ✅ Problem Solved: Unique Binary Search Trees (LeetCode 96) Today’s problem was a great example of how Dynamic Programming and mathematical patterns (Catalan Numbers) come together. 🔍 Key Insight: For every node chosen as root, the number of unique BSTs is: 👉 Left Subtrees × Right Subtrees This leads to the recurrence: dp[n] = Σ (dp[left] × dp[right]) 💡 What I learned: Breaking problems into smaller subproblems makes complex structures easier Recognizing patterns like Catalan Numbers is a game changer DP is not just about arrays, it's about thinking smart ⚡ Result: ✔️ Runtime: 0 ms (Beats 100%) ✔️ Clean and optimized solution Consistency is slowly turning into confidence 💪 #LeetCode #DataStructures #DynamicProgramming #CodingJourney #ProblemSolving #Java #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 15 of LeetCode Problem Solving Solved today’s problem — LeetCode #49: Group Anagrams 💻🔥 ✅ Approach: HashMap + Sorting ⚡ Time Complexity: O(n * k log k) 📊 Space Complexity: O(n * k) The task was to group strings that are anagrams of each other. 👉 I used a HashMap where: Key = sorted version of string Value = list of anagrams 💡 Key Idea: If two strings are anagrams, their sorted form will be the same. 👉 Core Logic: Convert string → char array Sort the array Use sorted string as key Store original string in map 💡 Key Learning: Transforming data (like sorting strings) can help in identifying patterns and grouping efficiently. Consistency is the key — learning something new every day 🚀 #Day15 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🌲 Day 38/75: Measuring the Diameter of a Binary Tree! Today’s LeetCode challenge was a step up in complexity: finding the Diameter of a Binary Tree. The diameter is the length of the longest path between any two nodes in a tree, which may or may not pass through the root. The Strategy: This problem is tricky because the longest path isn't always just the height of the left side plus the height of the right side at the root. It could be tucked away in one of the subtrees! I used a recursive Depth-First Search (DFS) that performs two tasks at once: Calculates Height: It returns the height of the current subtree to its parent. Updates Diameter: It calculates the path passing through the current node (leftHeight + rightHeight) and updates a global diameter variable if this path is the longest found so far. Performance: ✅ Runtime: 1 ms ✅ Complexity: $O(n)$ Time | $O(h)$ Space It’s a great example of how to extract multiple pieces of information from a single recursive pass. One more day closer to the 40-day mark! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #Algorithms #DataStructures #TechJourney
To view or add a comment, sign in
-
-
🚀 Day 2 of #100DaysOfCode — Majority Element (LeetCode 169) Today I solved the Majority Element problem using the Boyer-Moore Voting Algorithm — a brilliant technique that finds the majority element in O(n) time and O(1) space. 💡 Key Takeaways: • Learned how cancelling non-majority elements still preserves the majority • Understood why Boyer-Moore is more optimal than sorting or HashMap • Practiced writing clean and efficient Java code Problem: Find the element that appears more than ⌊n/2⌋ times in an array. Every day, one step closer to mastering Data Structures & Algorithms and becoming a better Software Engineer. 🔥 Consistency > Perfection. #100DaysOfCode #LeetCode #Java #DSA #CodingJourney #ProblemSolving #SoftwareEngineering #LearningInPublic #TechJourney
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