🚀 Daily DSA Practice – Day 40 | Path Sum & Backtracking in Binary Trees (Java) Continuing my Data Structures & Algorithms journey, today I focused on path-based tree problems, combining DFS recursion and backtracking to explore root-to-leaf and multi-path scenarios — a key pattern in coding interviews. 📌 Problems Solved (LeetCode): • 112. Path Sum – Checked existence of a root-to-leaf path matching a target sum • 113. Path Sum II – Stored all valid root-to-leaf paths using backtracking • 437. Path Sum III – Counted total paths using prefix-sum optimization with DFS 🎯 Key Learnings: ✔ Difference between existence check vs storing paths vs counting paths ✔ Practical use of backtracking to manage dynamic path lists ✔ Prefix-sum technique for optimizing multi-path calculations ✔ Improved understanding of recursion state management and edge cases These problems highlight how tree + backtracking patterns are widely used in search algorithms, hierarchical data analysis, and optimization tasks, making them highly relevant for product-based company interviews. #DSA #LeetCode #Java #BinaryTree #Backtracking #DFS #PathSum #ProblemSolving #InterviewPreparation #BackendDeveloper #SoftwareEngineer
Path Sum & Backtracking in Binary Trees (Java) - LeetCode Solutions
More Relevant Posts
-
𝐃𝐚𝐲 𝟏𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on grouping logic using arrays + hashing concepts 🗂️ and understanding different ways to build unique keys. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • 🔤 Group Anagrams 🔹 𝐆𝐫𝐨𝐮𝐩 𝐀𝐧𝐚𝐠𝐫𝐚𝐦𝐬 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟏 – 𝐒𝐨𝐫𝐭𝐢𝐧𝐠 𝐁𝐚𝐬𝐞𝐝 • 🔄 Converted each word into a char array • 📊 Sorted the characters • 🔑 Used the sorted string as a key in HashMap • 📦 Grouped words sharing the same sorted key 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟐 – 𝐅𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐀𝐫𝐫𝐚𝐲 𝐁𝐚𝐬𝐞𝐝 • 🔢 Created a frequency array of size 26 • 🧮 Built a unique key using character counts • ⚡ Used computeIfAbsent for cleaner insertion • 📌 Avoided sorting for better efficiency 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🧠 Anagrams share identical character distributions • 🔑 The way you build the key defines performance • ⚡ Frequency-array approach avoids O(k log k) sorting • 📊 Combining arrays with hashing improves efficiency 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Even in array problems, sometimes the real power lies in how you represent the data 🔑 15 days consistent 🔥 On to Day 16 🚀 #DSA #Arrays #Strings #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
✂️ DSA Practice — Remove All Occurrences of a Character (Recursive Approach) Today I solved Remove all occurrences of a character in a string using a recursive approach, focusing on careful index handling and in-place modification. 🔍 Key Learnings Recursion is useful even for string manipulation problems. When modifying a string in-place, index management is critical. After deletion, characters shift left — so the index should not advance. Clear base cases prevent infinite recursion. 🧠 Why This Problem Matters Strengthens understanding of recursion with mutable data structures. Helps build intuition for string traversal and modification. Common problem to test attention to detail and edge cases. 📌 Final Takeaway This problem highlights that recursion isn’t just about breaking problems down — it’s also about understanding how data changes during execution. #dsa #recursion #strings #problemSolving #codingpractice #java #datastructures #interviewpreparation #algorithms #100DaysOfCode #softwareengineering
To view or add a comment, sign in
-
-
🚀 Daily DSA Practice – Day 42 | Advanced Binary Tree Patterns (Java) Continuing my Data Structures & Algorithms journey, today I focused on advanced binary tree problems that combine recursion, divide-and-conquer, and path optimization techniques — commonly asked in product-based company interviews. 📌 Problems Solved (LeetCode): • 236. Lowest Common Ancestor of a Binary Tree – Identified shared ancestors using recursive DFS subtree checks • 124. Binary Tree Maximum Path Sum – Calculated the highest path sum using postorder traversal and global state tracking • 105. Construct Binary Tree from Preorder and Inorder Traversal – Rebuilt tree structure using divide-and-conquer logic with index mapping 🎯 Key Learnings: ✔ Mastered divide & conquer recursion patterns ✔ Understood how global variables help track optimal path values ✔ Improved intuition for tree reconstruction from traversals ✔ Strengthened problem-solving for hard-level recursive scenarios These problems highlight how advanced tree algorithms are critical in hierarchical data processing, compilers, and system-level architecture, making them extremely valuable for backend and product-engineering interviews. #DSA #LeetCode #Java #BinaryTree #Recursion #DivideAndConquer #TreeAlgorithms #ProblemSolving #InterviewPreparation #SoftwareEngineer #BackendDeveloper
To view or add a comment, sign in
-
Day 15 of My DSA Journey – Mastering Prefix Sum (Range Sum Query) Today, I worked on a classic and powerful concept in Data Structures: Prefix Sum Array 🔹 Problem: Given an array, answer multiple queries to find the sum between two indices efficiently. 🔹 Key Learning: Instead of recalculating the sum every time (O(n)), we can precompute a prefix array so that each query runs in O(1) time. => Formula: prefix[i] = prefix[i-1] + nums[i] => Range Sum: sumRange(left, right) = prefix[right] - prefix[left-1] (If left == 0, just return prefix[right]) This approach is widely used in: ✔️ Competitive Programming ✔️ Interview Questions ✔️ Real-world data analytics Feeling more confident with optimization techniques today Consistency really pays off! #Day15 #DSA #PrefixSum #LeetCode #CodingJourney #Java #ProblemSolving #LearningInPublic #TechGrowth
To view or add a comment, sign in
-
Contains Duplicate — LeetCode 217 Hi all 👋 Today this is my first post related to a DSA problem. Goal Check whether an array contains duplicate numbers or not. n = Length of array idx = Index of array element Brute Force Approach Select each element and compare it with all other elements in the array. If any same value is found, return "true"; otherwise return "false". Time Complexity: O(n²) Space Complexity: O(1) Reason: every element is compared with others. Better Approach (Sorting) If we sort the array, duplicate elements come next to each other. After sorting, we simply compare adjacent elements. 🕸 Trap Empty array or single element array (idx < n-1) Time Complexity: O(n log n) Space Complexity: Depends on the sorting algorithm. Optimized Approach (Using Set) Before moving forward, let’s recall one important data structure — Set. A set: - Performs operations in average O(1) time - Does not allow duplicates Approach: - Traverse the array from the first element. - Check if the element already exists in the set. - If yes → duplicate found → return "true". - Otherwise, add the element to the set. The key idea: if we encounter the same element again, it means a duplicate exists. Time Complexity: O(n) Space Complexity: O(n) (in worst case when no duplicates exist) 🔁 Trade-off In real-world problems, we often optimize for time complexity. - If extra space is allowed → use Set (best time). - If space is restricted → prefer Sorting. Whenever you see duplicate or frequency type problems, think about: ➡️ Sorting ➡️ HashSet / HashMap If I missed anything or if you have a better approach, please feel free to add it in the comments. Thanks for reading 🙌 #DSA #LeetCode #Java #CodingJourney #DataStructures #Algorithms #ProblemSolving #SoftwareEngineer #TechLearning #InterviewPreparation
To view or add a comment, sign in
-
Day 3 — DSA Practice Missed posting yesterday, but the consistency is still going strong. Solved 2 problems: • Two Sum II (Sorted Array)-167 Solved it in two ways: -Using HashMap -Using the Two Pointer approach It was interesting to compare both approaches. While HashMap works well, since the array is already sorted, the two-pointer method is cleaner and more space efficient. Time Complexity: -HashMap approach → O(n) time, O(n) space -Two Pointer approach → O(n) time, O(1) space Two pointers clearly felt more optimal here. • Number of Steps to Reduce a Number (Binary Representation) to One-1404 Initially, I tried converting the binary string using parseInt() and parseLong(), but it kept throwing overflow errors for large inputs. That made me realize that converting large binary strings directly isn’t always safe. Instead, I processed the string directly using: s.charAt(i) - '0' This avoids overflow and lets us simulate the operations efficiently. Time Complexity: -O(n), where n is the length of the binary string -O(1) extra space Key Takeaways: -Always consider constraints before choosing data types. -Sorted array problems often hint toward two-pointer solutions. -Small concepts (like converting char to int properly) can make a big difference. Learning > Just solving. Day 3 done. ✅ #DSA #Java #ProblemSolving #LearningInPublic #PlacementPreparation #Consistency
To view or add a comment, sign in
-
Day 9 – DSA Journey | Arrays 🚀 Today’s problem helped me understand backtracking with re-use of elements 🔁 and how recursion explores all valid combinations. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • ➕ Combination Sum 🔹 Combination Sum 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • 🔁 Used backtracking to build combinations • 🎯 Reduced the remaining target at each step • ♻️ Reused the same element by passing the current index again • 📌 Stored a valid path only when the remaining target becomes zero 𝐇𝐨𝐰 𝐢𝐭 𝐖𝐨𝐫𝐤𝐬 • ➡️ Start from a given index to avoid duplicate combinations • ➕ Add the current number to the path • 🔽 Recurse with reduced remaining sum • ⏪ Backtrack by removing the last added number 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🧠 Backtracking explores all valid paths systematically • ♻️ Passing the same index allows unlimited reuse of elements • 🎯 Base conditions control recursion flow • 🧹 Clean backtracking keeps the solution correct 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • ⏱ Time: Exponential (depends on number of combinations) • 📦 Space: O(target) (recursion depth + path) 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Backtracking isn’t about speed — It’s about exploring all possibilities correctly 🔍 On to Day 10 🔁🚀 #DSA #Arrays #Backtracking #Recursion #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day - 90 Binary Tree Maximum Path Sum The problem - Given the root of a binary tree, return the maximum path sum of any non-empty path. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. The path sum is the sum of the node values in the path. Brute Force - For each node, consider all possible paths starting from that node using DFS, calculate their sums, and track the maximum. This gives O(n²) time complexity as we explore multiple paths from each node with redundant calculations. Approach Used - •) Declare res = {root.val}. •) Call helper function: dfs(root , res). •) Return res[0]. Helper Function - dfs( Treenode node , int[] res) •) If node == null, return 0 (no contribution from null node). •) leftSum = Math.max(0, dfs(node.left, res)), taking max with 0 to ignore negative paths. •) rightSum = Math.max(0, dfs(node.right, res)), taking max with 0 to ignore negative paths. •) Update maximum sum, res[0] = Math.max(res[0], leftSum + rightSum + node.val), this considers path through current node connecting both subtrees. •) Return Math.max(leftSum, rightSum) + node.val, parent can use only one branch left or right. Complexity - Time - O(n), where n = number of nodes. Space - O(h), where h = height of tree. Note - At each node, we consider two scenarios: (1) the maximum path passing through this node (connecting both subtrees), which updates the global maximum, and (2) the maximum path extending from this node to its parent (using only one subtree), which is returned. We use Math.max(0, childSum) to ignore negative contributions, as excluding negative paths yields better sums. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟐𝟒 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on applying binary search in a 2D matrix by treating it like a flattened sorted array. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Search a 2D Matrix 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟏 – 𝐓𝐨𝐩-𝐑𝐢𝐠𝐡𝐭 𝐒𝐜𝐚𝐧 • Start from the top-right corner • Move left if the current value is greater • Move down if the current value is smaller • Time Complexity: O(n + m) 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟐 – 𝐑𝐨𝐰-𝐖𝐢𝐬𝐞 𝐁𝐢𝐧𝐚𝐫𝐲 𝐒𝐞𝐚𝐫𝐜𝐡 • Identify the possible row • Apply binary search inside that row • Time Complexity: O(n log m) 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟑 – 𝐅𝐥𝐚𝐭𝐭𝐞𝐧𝐞𝐝 𝐁𝐢𝐧𝐚𝐫𝐲 𝐒𝐞𝐚𝐫𝐜𝐡 • Treat matrix as a 1D sorted array • Range: 0 to (n × m − 1) • Convert index → row = mid / m, col = mid % m • Apply standard binary search 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • A 2D matrix can be treated as 1D with index mapping • Binary search is about reducing the search space logically • Index math simplifies multidimensional problems • Choosing the right abstraction makes problems easier 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(log(n × m)) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Sometimes the trick is not searching in 2D — it’s thinking in 1D. 24 days consistent. On to Day 25 🚀 #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟯𝟳/𝟳𝟱 | 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝟳𝟱 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 2095. Delete the Middle Node of a Linked List 𝗗𝗶𝗳𝗳𝗶𝗰𝘂𝗹𝘁𝘆: Medium 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘂𝗺𝗺𝗮𝗿𝘆: You are given the head of a linked list. Delete the middle node and return the head of the modified list. The middle node is defined as the ⌊n / 2⌋th node using 0-based indexing. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Use the slow and fast pointer technique. The fast pointer moves two steps at a time while the slow pointer moves one step. When the fast pointer reaches the end, the slow pointer is positioned just before the middle node. I then removed the middle node by updating the next pointer of the slow node. 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 𝗔𝗻𝗮𝗹𝘆𝘀𝗶𝘀: • Time Complexity: O(n), since the list is traversed once • Space Complexity: O(1), no extra data structures are used 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Two-pointer techniques help solve linked list problems efficiently without needing extra memory. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝗟𝗶𝗻𝗸: https://lnkd.in/gHXEprUE #Day37of75 #LeetCode75 #DSA #Python #Java #MachineLearning #DataScience #ML #DataAnalyst #LearningInPublic #TechJourney #LeetCode
To view or add a comment, sign in
-
Explore related topics
- Java Coding Interview Best Practices
- Key DSA Patterns for Google and Twitter Interviews
- Leetcode Problem Solving Strategies
- Common Algorithms for Coding Interviews
- Approaches to Array Problem Solving for Coding Interviews
- Why Use Coding Platforms Like LeetCode for Job Prep
- DSA Preparation Tips for First Interview Round
- Common Data Structure Questions
- Steps to Become a Back End Developer
- Learning Path for Aspiring Backend Developers
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