🚀 Day 399 of #500DaysOfCode 🔹 Problem: 129. Sum Root to Leaf Numbers 🔹 Difficulty: Medium 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given the root of a binary tree containing digits (0–9), each root-to-leaf path represents a number. Our task is to find the sum of all numbers formed by these root-to-leaf paths. 💡 Key Idea: We can use Depth-First Search (DFS) to traverse the tree. As we go deeper, we build the current number by multiplying by 10 and adding the current node’s value. When we reach a leaf node, we add that full number to our total sum. ⚙️ Approach: 1️⃣ Start DFS from the root with currentSum = 0. 2️⃣ At each step, update currentSum = currentSum * 10 + node.val. 3️⃣ When reaching a leaf node, return that number. 4️⃣ Combine left and right subtree results to get the total sum. ✅ Example: Input: root = [1,2,3] Output: 25 Paths: 12 + 13 = 25 📘 Lesson Learned: Sometimes, problems that seem about “trees” are really about number construction — a great reminder that recursion can elegantly combine logic with mathematics 🌱 #Day399 #Java #LeetCode #BinaryTree #DFS #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #500DaysOfCode
Java solution for Sum Root to Leaf Numbers using DFS
More Relevant Posts
-
🚀 Day 398 of #500DaysOfCode 🔹 Problem: 914. X of a Kind in a Deck of Cards 🔹 Difficulty: Easy 🔹 Language Used: Java ☕ 🧩 Problem Summary: Given a deck of cards where each card has an integer, the goal is to check if we can divide the deck into groups such that: Each group has exactly X cards, where X > 1, and All cards in a group have the same integer. If such a partition is possible, return true — otherwise, return false. 💡 Key Idea: The solution relies on finding the greatest common divisor (GCD) of all card frequencies. If the GCD of all counts is greater than 1, we can form valid groups; otherwise, we can’t. ⚙️ Approach: 1️⃣ Count the frequency of each card using a HashMap. 2️⃣ Compute the GCD of all frequency values. 3️⃣ If GCD > 1, return true; else, false. 🧠 Concepts Used: HashMap GCD (Euclidean Algorithm) Frequency Counting ✅ Example: Input: [1,2,3,4,4,3,2,1] → Output: true Input: [1,1,1,2,2,2,3,3] → Output: false 📘 Lesson Learned: Even simple-looking problems can hide elegant mathematical patterns. Understanding GCD turned out to be the key! 💪 #Day398 #Java #LeetCode #ProblemSolving #CodingChallenge #LearnEveryday #Programming #Developer #100DaysOfCode #500DaysOfCode
To view or add a comment, sign in
-
-
🔥 LeetCode Day--- 4 | “Median of Two Sorted Arrays” (Hard, Java) Today’s challenge was one of those that really test your logic, patience, and understanding of binary search. This problem wasn’t about just merging two sorted arrays — it was about thinking smarter 🧠. Instead of brute-forcing through both arrays (O(m+n)), I implemented a binary partition approach to achieve O(log(min(m, n))) efficiency 💡 What I learned today: Always choose the smaller array for binary search — it makes the partition logic simpler. Handle boundaries carefully with Integer.MIN_VALUE and Integer.MAX_VALUE. The goal is to find the perfect partition where: Left half ≤ Right half Elements are balanced across both arrays Once that’s done → median can be easily calculated! ✅ Result: Accepted | Runtime: 0 ms 🚀 Hard problem turned into a logic puzzle that was actually fun to solve! 🧩 Concepts Strengthened: Binary Search Partitioning Logic Edge Case Handling Mathematical Thinking #LeetCode #Day4 #Java #BinarySearch #ProblemSolving #CodingChallenge #DataStructures #Algorithms #CodeEveryday #DeveloperJourney #TechLearning #LeetCodeHard #CodingCommunity
To view or add a comment, sign in
-
-
🔥 Day 20 | LeetCode Challenge – Decode Ways (Problem #91) Today’s challenge involved decoding an encoded numeric string where each number represents a letter (A–Z). The task was to determine how many possible ways the message can be decoded. 💡 Core Concept: Each number from 1–26 maps to letters A–Z, and the challenge lies in handling overlapping combinations and invalid encodings (like “06”). 📘 Approach: Implemented a Dynamic Programming (DP) solution in Java. Used an integer array dp[] to store the number of decoding ways up to each position. Considered both single-digit and two-digit decodings: Single-digit → valid if between 1 and 9. Two-digit → valid if between 10 and 26. The result was stored in dp[n], representing all valid decoding combinations. ⚙️ Algorithm Used: Dynamic Programming 🧾 Language: Java ⚡ Runtime: 1 ms (Beats 83.21%) 💾 Memory: 43.33 MB 🧠 Insight: Breaking the decoding process into smaller subproblems allowed efficient computation of possible message interpretations. This problem elegantly demonstrates how DP handles overlapping substructures in combinatorial challenges. #Day20 #LeetCode #DecodeWays #DynamicProgramming #JavaDeveloper #100DaysOfCode #ProblemSolving #CodingChallenge #DataStructuresAndAlgorithms #ProgrammingJourney #TechLearning #AlgorithmDesign
To view or add a comment, sign in
-
-
💡 LeetCode #167 — Two Sum II (Input Array Is Sorted) Today I solved LeetCode Problem 167: Two Sum II — Input Array Is Sorted 🎯 Problem Summary: You are given a sorted array and a target. Return the 1-indexed positions of the two numbers that add up to the target. You must use O(1) extra space. Key Idea: Use the two-pointer technique 👈👉 Start with one pointer at the beginning (left) and one at the end (right). If the sum is too large → move right leftward. If the sum is too small → move left rightward. Stop when you find the pair. This works because the array is already sorted. #LeetCode #Java #DSA #TwoPointers #Algorithms #ProblemSolving #CodingChallenge
To view or add a comment, sign in
-
-
#Day_31 Today’s challenge was an interesting matrix binary search problem — “Find a Peak Element II”-> it's a medium level question. The task: Given a 2D grid, find any element that’s strictly greater than its top, bottom, left, and right neighbors. A brute-force solution would check every element’s neighbors — but that’s O(m × n). Instead, I used a binary search on columns to cut the search space efficiently. Here’s the idea: Pick the middle column. Find the maximum element in that column. Compare it with its left and right neighbors. If it’s greater than both — you’ve found a peak. Otherwise, move to the side that has a larger neighbor (since a peak must exist there). This clever approach brings the complexity down to O(m × log n) — a huge win on large matrices. This problem was a great reminder that binary search isn’t just for 1D arrays — it can be applied creatively in multiple dimensions too #Coding #LeetCode #Java #BinarySearch #ProblemSolving #LearningEveryday
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #111 — Minimum Depth of Binary Tree 📘 Problem: Given the root of a binary tree, find its minimum depth — the shortest path from the root node down to the nearest leaf node. A leaf node is one that has no children. Example: Input → [3,9,20,null,null,15,7] Output → 2 Explanation → The shortest path is 3 → 20 → 7. 🧠 My Approach: I used a simple recursive DFS approach to calculate the minimum depth. 1️⃣ If the node is null, return 0. 2️⃣ Recursively find the left and right subtree depths. 3️⃣ If one of the subtrees is missing, return the depth of the existing one. 4️⃣ Otherwise, return the smaller of the two depths + 1. 💡 What I Learned: ✅ The difference between height and depth in trees ✅ How to handle null nodes properly in recursion ✅ The importance of handling edge cases when one subtree is missing 💻 Language Used: Java 🔍 Approach Type: Recursive DFS #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
📌 Day 12/100 - Concatenation of Array (LeetCode 1929) 🔹 Problem: Given an integer array nums, create a new array ans such that: ans[i] = nums[i] ans[i + n] = nums[i] where n is the length of nums. In short, we need to concatenate the array with itself to form a new array of size 2n. 🔹 Approach: First, determine the length n of the array. Create a new array newArray of size 2n. Loop through nums once: Assign each element twice — once at position i and once at position i + n. Finally, return the concatenated array. 🔹 Key Learning: Reinforced the concept of array indexing and iteration. Practiced efficient array manipulation in Java. Sometimes, the simplest logic is the cleanest — clarity beats complexity! 💡 Every solved problem adds a layer of confidence and consistency 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
🌟 Day 44 – LeetCode Practice Problem: Product of Array Except Self (LeetCode #238) 📌 Concept: Given an integer array, create a new array where each element equals the product of all other elements except itself, without using division. 🧠 My Approach: First pass → compute prefix products (multiply everything before current index) Second pass → compute suffix products (multiply everything after current index) Combine both to get the result for each index efficiently No extra multiplication array used — optimized and clean logic ⚡ This avoids division and runs in linear time — exactly what the problem demands ✅ 📈 Result: ✅ Accepted ⚡ Runtime: 2 ms (Beats ~87%) 📦 Memory: Efficient usage 💡 Key Learning: This problem reinforces the power of prefix & suffix computation — a common trick in array manipulation + interview favorite. Great way to improve problem-solving without relying on brute force or division. --- 🚀 Growing stronger every day in DSA! #LeetCode #DSA #Java #ProblemSolving #PrefixSuffix #CodingJourney #ArrayProblems #LearningMindset
To view or add a comment, sign in
-
-
Day 39 — Ones and Zeroes (0–1 Knapsack Variation) Problem: 474. Ones and Zeroes Difficulty: Medium Language: Java Status: Solved Problem Summary: Given an array of binary strings strs and two integers m and n, find the maximum subset size such that the total number of '0's ≤ m and total '1's ≤ n. Key Concept: This is a 2D 0–1 Knapsack problem, where: Each string represents an item with two “weights”: count of '0's and '1's. We must maximize the number of strings (the “value”) within the constraints of available m and n. Algorithm Steps: Count zeros and ones for each string. Iterate backwards (to avoid overwriting previous states). Update dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1) for all valid i, j. Time Complexity: O(len(strs) * m * n) Space Complexity: O(m * n) Learning Takeaway: This problem strengthens understanding of multidimensional dynamic programming. The backward iteration pattern is crucial in 0–1 Knapsack-style DP to prevent reuse of the same item. #Day39 #100DaysOfCode #LeetCode #DynamicProgramming #Knapsack #DP #Java #Algorithms #CodingChallenge #ProblemSolving #DSA
To view or add a comment, sign in
-
-
🚀 Day 73 | DSA with Java Today, I practiced the Monotonic Array Problem — a simple but very important concept for pattern detection in arrays. 📈📉 --- 🔹 Problem Statement: An array is monotonic if it is either: Entirely non-increasing (each element ≤ previous), or Entirely non-decreasing (each element ≥ previous) Example: [1, 2, 2, 3] → Monotonic (non-decreasing) [6, 5, 4, 4] → Monotonic (non-increasing) [1, 3, 2] → ❌ Not monotonic --- ⚙️ Approach Used: 1. Check if the array is increasing 2. Check if the array is decreasing 3. If either is true → array is monotonic Time Complexity: O(n) Space Complexity: O(1) --- 🧠 Key Learnings: ✅ Strengthened understanding of array trends ✅ Used simple linear scanning to detect monotonicity ✅ Helpful for sliding window, binary search, and peak problems --- #DSA #Java #MonotonicArray #Arrays #ProblemSolving #LogicBuilding #100DaysOfCode #GitHub #Coding
To view or add a comment, sign in
-
Explore related topics
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