Consistency is starting to compound 💻🌱🔥 Solved another problem today—this time from Binary Trees 🌳🚀 Completed Root to Leaf Paths with 100% accuracy (1115/1115 test cases passed) 💯✅ 🔍 Problem Insight: The task was to return all possible paths from the root node to every leaf node in a binary tree 🌳➡️🍃 🧠 My Approach: 👉 Used DFS (Depth-First Search) with recursion 🔁 👉 Maintained a currentPath list to track nodes while traversing 🛤️ 👉 At each node, added the current value to the path ➕ 👉 If a leaf node was reached, stored a copy of the current path in the final answer 📌 👉 Used backtracking by removing the last node after returning from recursion 🔙 ✨ Why this approach works well: ✔ Natural fit for tree traversal 🌳 ✔ Explores every root-to-leaf path efficiently 🚀 ✔ Backtracking keeps memory controlled 🧠 ✔ Clean recursive structure and easy to follow 🧼 📊 Complexity: ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(h) recursion stack (plus output space for storing all paths) 📦 💡 Key Takeaway: Tree problems become much simpler when you think in terms of: 👉 traversal pattern 👉 path tracking 👉 backtracking DFS + recursion continues to be one of the cleanest ways to solve path-based tree problems 🎯🌳 One more problem solved, one more concept strengthened 💪📈🔥 #BinaryTree #Trees #Recursion #DFS #Java #DataStructures #DSA #ProblemSolving #CodingJourney #100DaysOfCode #SoftwareEngineering #Programming #TechGrowth 💻🌳🚀
Solved Binary Tree Root to Leaf Paths with DFS and Recursion
More Relevant Posts
-
Day 76/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Lowest Common Ancestor of a Binary Tree A fundamental tree problem that builds strong recursion intuition. Problem idea: Find the lowest node in the tree that has both given nodes as descendants. Key idea: DFS + recursion (bottom-up approach). Why? • Each subtree can independently tell if it contains p or q • Combine results while backtracking • First node where both sides return non-null → answer How it works: • If current node is null / p / q → return it • Recursively search left and right subtree • If both left & right are non-null → current node is LCA • Else return the non-null side Time Complexity: O(n) Space Complexity: O(h) (recursion stack) Big takeaway: Tree problems often rely on post-order traversal + combining child results. Understanding this pattern unlocks many binary tree problems. 🔥 Day 76 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinaryTree #Recursion #DFS #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
📌 Median of Two Sorted Arrays Platform: LeetCode #4 Difficulty: Hard ⚙️ Approach • Apply binary search on the smaller array for efficiency • Define search space from 0 to n1 • Partition both arrays such that: – Left half contains (n1 + n2 + 1) / 2 elements – Right half contains remaining elements • Identify boundary elements: – l1, l2 → left side elements – r1, r2 → right side elements • Check valid partition: – l1 <= r2 and l2 <= r1 • If valid: – For even length → median = average of max(left) and min(right) – For odd length → median = max(left) • If not valid: – If l1 > r2, move left – Else move right 🧠 Logic Used • Binary Search on partition index • Dividing arrays into balanced halves • Handling edge cases using boundary values • Achieving optimal O(log(min(n1, n2))) time complexity 🔗 GitHub: https://lnkd.in/g_3x55n8 ✅ Day 36 Completed – Revised advanced binary search and partition-based problem. #100DaysOfCode #Java #DSA #ProblemSolving #CodingJourney #Algorithms #DataStructures #LeetCode #CodingPractice #CodeEveryDay #BinarySearch #ArrayProblems
To view or add a comment, sign in
-
-
🚀 Day 86 — Prefix Sum Pattern (Introduction) Today I started learning the Prefix Sum pattern — a fundamental technique for array problems where decisions at a given index depend on the sum of previous elements. Unlike sliding window, prefix sum handles negative numbers gracefully. 📌 What is Prefix Sum? At index i, the prefix sum is the sum of all elements from the start up to i-1. It stores “historical information” to make efficient decisions. 🧠 Why Prefix Sum > Sliding Window for Negatives? Sliding window fails with negatives because removing a negative actually increases the sum — breaking the logic of expanding/shrinking. Prefix sum remains effective. 📊 Four Categories of Prefix Sum Problems: 1️⃣ Left‑Right Comparisons (e.g., Pivot Index) → Can often be solved with simple variables (no extra arrays). 2️⃣ Exact Sums (Subarray Sum = K) → Requires a HashMap to store and lookup previous prefix sums. 3️⃣ Shortest Window with Sum ≥ K (with negatives) → Needs a Deque (double‑ended queue). 4️⃣ Range Sum Queries → Advanced techniques like Merge Sort on prefix array. 🔧 General Template: Initialize data structure (variable, array, or HashMap). Loop through the array, updating prefix information. Check problem‑specific condition. ⚡ Optimization Insight (Pivot Index Example): Instead of storing both prefix and suffix arrays, use: Total Sum = Left Sum + arr[i] + Right Sum → Right Sum = Total Sum - Left Sum - arr[i] This finds the pivot using only O(1) space. 💡 Takeaway: Prefix sum is a pattern, not just an algorithm. Recognizing when to use it — especially with negative numbers — unlocks efficient solutions for subarray sum problems. No guilt about past breaks — just adding another powerful pattern to the toolkit. #DSA #PrefixSum #ArrayPatterns #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem extended the previous one by introducing duplicates in a rotated sorted array. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Minimum in Rotated Sorted Array II 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used modified binary search • Compared nums[mid] with nums[right] Logic: • If nums[mid] > nums[right] → minimum is in right half • If nums[mid] < nums[right] → minimum is in left half (including mid) • If equal → cannot decide, so shrink search space (right--) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Duplicates can break standard binary search logic • When unsure, safely reduce the search space • Edge cases often define the complexity of the problem • Small changes in conditions can affect performance 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Average Time: O(log n) • Worst Case: O(n) (due to duplicates) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When the data becomes ambiguous, focus on reducing the problem safely instead of forcing a decision. 55 days consistent 🚀 On to Day 56. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 79/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Flatten Binary Tree to Linked List A powerful tree transformation problem using pointer manipulation. Problem idea: Convert a binary tree into a linked list in-place following preorder traversal. Key idea: Iterative traversal + rewiring (similar to Morris traversal idea). Why? • We need preorder sequence (Root → Left → Right) • Instead of extra space, we modify pointers in-place • Efficient and avoids recursion stack How it works: • Traverse using a pointer curr • If left child exists: → Find rightmost node of left subtree → Connect it to current’s right subtree → Move left subtree to right → Set left = null • Move to next node (curr.right) Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Tree problems can often be optimized using in-place pointer rewiring, avoiding extra space. 🔥 This pattern is very useful for tree flattening and traversal optimizations. Day 79 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #BinaryTree #MorrisTraversal #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🔥 DSA Challenge – Day 128/360 🚀 📌 Topic: Recursion 🧩 Problem: Letter Combinations of a Phone Number 💡 Problem Statement: Given a string of digits (2–9), return all possible letter combinations that the number could represent based on the classic phone keypad mapping. 🔍 Example: Input: "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] 💡 Approach: Backtracking (Recursion) We treat this like a decision tree: Each digit maps to multiple characters For every digit, we try all possible letters Build combinations step-by-step using recursion 👉 Key Idea: Choose → Explore → Backtrack Use StringBuilder for efficient string manipulation ⚙️ Steps: Create a mapping for digits → letters Start recursion from index 0 For each digit: Loop through its mapped letters Add letter to current string Move to next digit Backtrack (remove last character) 🚀 Code Highlights: ✔️ Base case: when index reaches end → add combination ✔️ Efficient backtracking using StringBuilder ✔️ Avoids extra space by modifying same string ⏱️ Time Complexity: O(4^N) 📦 Space Complexity: O(N) (recursion stack) Master this → You master recursion 🔥 #DSA #Java #Backtracking #CodingInterview #LeetCode #128DaysOfCode #Programming #Tech #ProblemSolving
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
Another day of showing up, learning, and getting sharper 💻🔥 Solved Boundary Traversal of Binary Tree today and got it accepted with 100% accuracy (1111/1111 test cases passed) 💯✅ This was a really good problem for understanding how to break one tree traversal into multiple smaller traversals and combine them cleanly 🌳🧠 🔍 Problem Insight: The goal was to print the boundary nodes of a binary tree in anti-clockwise direction 🔄🌳 That means covering: 👉 Root node 👉 Left boundary (excluding leaf nodes) 👉 All leaf nodes (left to right) 🍃 👉 Right boundary (excluding leaf nodes, in reverse) 🧠 My Approach: Instead of forcing everything into one traversal, I split the problem into 3 clean helper functions ✨ 👉 Left Boundary Traversal Traversed the left side while skipping leaf nodes ⬅️🌿 👉 Leaf Node Traversal Collected all leaf nodes using DFS from left to right 🍃 👉 Right Boundary Traversal Traversed the right side and added nodes in reverse order to maintain anti-clockwise flow ➡️🔄 Then combined everything in sequence to build the final boundary traversal 🎯 ✨ Why this approach works well: ✔ Breaks a complex problem into manageable parts 🧩 ✔ Avoids duplicate leaf nodes 🚫🍃 ✔ Clean recursive design 🌳 ✔ Easy to debug and reason about 🧠 📊 Complexity: ⏱️ Time Complexity: O(n) 💾 Space Complexity: O(h) recursion stack 💡 Key Takeaway: Tree problems often become much simpler when you stop thinking in terms of “one big traversal” and instead split them into smaller focused traversals 🎯 Decompose well → solve cleanly 🚀 One more tree problem down, many more to go 🌳💪🔥 #BinaryTree #Trees #TreeTraversal #Java #Recursion #DFS #DataStructures #DSA #ProblemSolving #CodingJourney #100DaysOfCode #SoftwareEngineering #Programming 💻🌳🚀
To view or add a comment, sign in
-
-
🚀 Day 11 — Streams, Partitioned Logs, and Consumer Groups Queues are useful when work needs to be processed asynchronously. But Day 11 helped me understand a different pattern: 👉 when events need to be stored, replayed, and consumed by multiple independent systems. That is where streams and partitioned logs become important. Because in event-driven systems, data is not just passed from one service to another. It becomes a continuous flow that different consumers may process in different ways. Today’s focus was: Streams, Partitioned Logs, and Consumer Groups 📊 What I covered today 📘 📜 Append-only event logs 🧩 Partitioning for scale 🔑 Ordering guarantees and key-based routing 👥 Consumer groups and offset tracking 🔁 Replay and recovery 📉 Lag monitoring and backpressure What stood out to me ✅ Append-only logs make replay, auditing, and recovery much easier ✅ Partitioning improves throughput, but ordering is only guaranteed within a partition ✅ Key-based routing helps keep related events together ✅ Consumer groups allow multiple applications to process the same stream independently ✅ Offset tracking is critical because consumers should resume from where they stopped ✅ Consumer lag is one of the most important signals in stream processing systems I also implemented a small Partitioned Log with Consumer Offsets sample in Python and Java to make the concept more practical. 🛠️ ➡️ Git: https://lnkd.in/dPKzP2B5 That helped me understand a simple but important idea: 📌 Streams are not just queues 📌 Replay is a feature, not a bug 📌 Offset tracking is what makes recovery possible This is one of those topics that becomes much clearer when you build even a small version of it. Producing events is simple, but handling partitions, offsets, replay, and lag is where the real system design thinking starts. System Design is slowly becoming less about moving data from one place to another and more about building data flows that are scalable, replayable, and reliable under load. On to Day 12 📈 #SystemDesign #DistributedSystems #BackendEngineering #SoftwareEngineering #ScalableSystems #Streams #EventStreaming #PartitionedLogs #ConsumerGroups #OffsetTracking #Kafka #ApacheKafka #EventDrivenArchitecture #MessageQueues #AsyncProcessing #DataStreaming #StreamProcessing #Backpressure #ConsumerLag #Microservices #SystemArchitecture #BackendDevelopment #CloudComputing #Java #Python
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