🗓️ Day 32 / 100 – Binary Tree Maximum Path Sum 🌳💻 Today’s challenge pushed my recursion and problem-solving skills to the limit. I worked on finding the Maximum Path Sum in a Binary Tree — a classic yet tricky problem that tests your understanding of recursion, global state management, and tree traversal. 🔁 It took me 10 submissions to finally get it right! Each attempt helped me uncover a new insight — from handling negative values to understanding how and where to update the global maximum. 💡 The major improvement came on the 11th attempt, when I replaced the static global variable with a local reference (int[] maxSum). This small design change made my code cleaner, reusable, and thread-safe — a great reminder that writing correct code is one thing, but writing robust code is another. 📈 Key Learnings: Manage global state carefully in recursive problems. Use reference wrappers (like int[] or small helper classes) to avoid side effects. Debugging recursion is easier when you visualize each return value and what it represents. 🧠 Code snippet (improved version): public int maxPathSum(TreeNode root) { int[] maxSum = {Integer.MIN_VALUE}; maxPath(root, maxSum); return maxSum[0]; } 🚀 Reflection: Persistence pays off! Every failed attempt was just one step closer to understanding the problem deeply. #100DaysOfCode #Day32 #Java #DSA #LeetCode #CodingJourney #LearningInPublic #ProblemSolving #BinaryTree
"Overcoming challenges in Binary Tree Maximum Path Sum problem"
More Relevant Posts
-
🧠 LeetCode Day 97 — Path Sum (Problem 112) Today’s challenge was about checking whether a binary tree has a root-to-leaf path such that adding up all the values along the path equals a given sum. 🔍 Problem Description: Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that the sum of the node values equals targetSum. Otherwise, return false. 💡 Approach: Traverse the tree recursively. Subtract the current node’s value from targetSum. When a leaf node is reached, check if the remaining sum equals zero. Use Depth First Search (DFS) to explore all paths. 🚀 Key Learnings: Strengthened understanding of recursive tree traversal. Practiced handling base cases in recursion effectively. Improved clarity on root-to-leaf path logic in binary trees. 🌳 #Day97 of #100DaysOfCode Each challenge adds a new layer to my problem-solving skills. Binary tree problems like this sharpen the recursive mindset — thinking from root to leaf and back up! 💪 #LeetCode #CodingChallenge #Java #100DaysOfCode #BinaryTree #ProblemSolving #Recursion
To view or add a comment, sign in
-
-
✅ Just solved LeetCode #654 — Maximum Binary Tree 📘 Problem: Given an integer array without duplicates, the task is to build a maximum binary tree. The construction rules are: 1️⃣ The root is the maximum element in the array. 2️⃣ The left subtree is built recursively from elements to the left of the maximum. 3️⃣ The right subtree is built recursively from elements to the right of the maximum. Example: Input → [3,2,1,6,0,5] Output → [6,3,5,null,2,0,null,null,1] 🧠 My Approach: I solved this problem using a recursive divide-and-conquer approach. 1️⃣ Find the index of the maximum element in the given range — this becomes the root. 2️⃣ Recursively build the left subtree from the subarray before the maximum element. 3️⃣ Recursively build the right subtree from the subarray after the maximum element. 💡 What I Learned: ✅ How recursion naturally fits into tree construction problems ✅ The concept of divide and conquer applied to array-based tree building ✅ How to translate problem definitions into direct recursive structure #LeetCode #Java #DSA #BinaryTree #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
#Day_34 Today’s problem was a satisfying one to solve — “Single Element in a Sorted Array” 🔍 Given a sorted array where every element appears twice except for one unique element, the task is to identify that single element. At first, it seems like a simple linear scan could do the job — and yes, it can. But I focused on building a clean and logical O(n) approach before thinking about optimization 🧠 Approach We observe that: Every element appears in pairs, and because the array is sorted, duplicates are adjacent. The unique element is the only one that doesn’t match its left or right neighbor. We can handle three cases: First element: If it’s not equal to the next one → it’s the single element. Last element: If it’s not equal to the previous one → it’s the single element. Middle elements: If an element is different from both its previous and next → that’s our answer. This way, we can detect the single element in just one pass through the array ⏱ Complexity Time: O(n) — We traverse the array once. Space: O(1) — No extra memory used. 💬 Reflection This problem is a good reminder that not every efficient solution has to start complex. Sometimes, the cleanest brute-force version gives a perfect foundation for further optimization — in this case, even leading to an O(log n) binary search variant. Each problem in this challenge pushes me to think deeper about patterns, structure, and clarity in problem-solving. #CodingJourney #LeetCode #ProblemSolving #100DaysOfCode #Java #LearnByDoing #DSA
To view or add a comment, sign in
-
-
📌 Day 8/100 - Search Insert Position (LeetCode 35) 🔹 Problem: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be inserted in order. 🔹 Approach: I used a binary search approach for efficiency 🔍 1️⃣ Start with two pointers — low and high. 2️⃣ Find the mid index and compare nums[mid] with the target. 3️⃣ If target equals nums[mid], return mid. 4️⃣ If target is smaller, move the high pointer left. 5️⃣ If target is greater, move the low pointer right. 6️⃣ When the loop ends, low gives the correct insert position. 🔹 Key Learning: Binary Search saves time — reducing O(n) to O(log n)! Understanding the condition when to move left/right is key. Even simple problems sharpen logical precision and boundary handling. Each problem strengthens the logic muscle 🧠 — one step closer to mastering algorithms! 💪 #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingJourney #LearnByDoing
To view or add a comment, sign in
-
-
🔢 Day 47 of #LeetCode100DaysChallenge Solved LeetCode 79: Word Search — a classic backtracking problem that beautifully blends recursion and grid traversal. 🧩 Problem: Given a 2D grid of characters and a word, determine if the word can be formed using sequentially adjacent cells (up, down, left, right), where each cell can be used only once. 💡 Approach Used — Backtracking (DFS): 1️⃣ Start from each cell that matches the first character. 2️⃣ Explore in all four directions recursively. 3️⃣ Temporarily mark visited cells to avoid reuse. 4️⃣ If the entire word is matched, return true; otherwise, backtrack. ⚙️ Complexity: Time: O(N × 4ᴸ) — where N is the total number of cells, and L is the word length. Space: O(L) — recursion depth. ✨ Key Takeaways: ✅ Strengthened understanding of recursion and backtracking. ✅ Learned to manage visited states effectively in grid problems. ✅ Great exercise in applying DFS to real-world matrix traversal cases. #LeetCode #100DaysOfCode #Java #Backtracking #Recursion #ProblemSolving #DSA #WomenInTech #CodingJourney
To view or add a comment, sign in
-
-
🚀 Just Solved LeetCode #1367 — Linked List in Binary Tree 📘 Problem: Given the head of a linked list and the root of a binary tree, determine whether all the elements of the linked list appear as a downward path in the binary tree. Downward means starting from any node and moving only to child nodes. Example: Input → head = [4,2,8], root = [1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3] Output → true Explanation → Nodes in blue form a subpath in the binary tree. 🧠 My Approach: I used recursion to check whether the linked list sequence can be found starting from any node in the binary tree. 1️⃣ For each node in the tree, check if the list starting from `head` matches the downward path from that node. 2️⃣ If not, recursively check the left and right subtrees. 3️⃣ Used a helper function `checkPath()` to verify if a valid path continues as the recursion goes deeper. 💡 What I Learned: ✅ How to combine linked list and binary tree traversal logic ✅ How recursion can efficiently check multiple starting points ✅ Improved my understanding of tree path traversal and backtracking logic #LeetCode #Java #DSA #BinaryTree #LinkedList #CodingUpdate #LearningByDoing
To view or add a comment, sign in
-
-
🌟 Day 84 of My #100DaysOfCode Challenge 🧩 Problem: LeetCode 108 – Convert Sorted Array to Binary Search Tree 💭 Understanding the Problem Given a sorted array, we need to convert it into a height-balanced Binary Search Tree (BST) — meaning the difference in height between the left and right subtrees of every node should not exceed one. 📘 Example: Input: nums = [-10, -3, 0, 5, 9] Output: [0, -3, 9, -10, null, 5] The middle element (0) becomes the root, left half forms the left subtree, and the right half forms the right subtree. 🧠 Key Idea Pick the middle element as the root for balance. Recursively repeat the same for left and right halves. This approach ensures that the BST remains balanced. ⚙️ Complexity Analysis Time Complexity: O(n) — each element is processed once. Space Complexity: O(log n) — recursion stack in a balanced tree. ✨ Takeaway This problem beautifully combines recursion and binary tree logic, showcasing how dividing the array strategically helps maintain balance in a BST. 💬 "Balanced structures are key to efficiency — both in code and in life!" 😄 #Day84 #LeetCode #Java #DSA #BinaryTree #CodingChallenge #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
✅ Day 51 of LeetCode Medium/Hard Edition Today’s challenge was about generating numbers whose prime factors are limited to 2, 3, and 5 — the classic Ugly Number II problem! 💫 📦 Problem: An ugly number is a positive integer whose prime factors are restricted to 2, 3, and 5. Given an integer n, return the nth ugly number. 🔗 Problem Link: https://lnkd.in/gS9EKbbd ✅ My Submission: https://lnkd.in/gnTe_zvY 💡 Thought Process: To generate the sequence in ascending order, we can use a Min-Heap + HashSet approach: Start from 1, the first ugly number. Repeatedly multiply it by {2, 3, 5} to generate new candidates. Maintain a min-heap to always pick the next smallest number. Use a set to avoid duplicates. After popping n elements, the last popped value is our nth ugly number. ⏱ Complexity: Time: O(n log n) Space: O(n) 🔥 Key Takeaway: Combining heaps and hashing efficiently maintains order and uniqueness in sequence generation. A great demonstration of how priority queues can systematically build ordered numeric sequences — step by step! #LeetCodeMediumHardEdition #100DaysChallenge #Heap #HashSet #ProblemSolving #DataStructures #CodingJourney #Java #LeetCode
To view or add a comment, sign in
-
-
📌 Day 15/100 - Majority Element (LeetCode 169) 🔹 Problem: Given an array of integers nums, find the element that appears more than ⌊ n/2 ⌋ times — the majority element. It’s guaranteed that such an element always exists in the array. 🔹 Approach: Implemented the Boyer–Moore Voting Algorithm, a clever and efficient approach: Assume the first element as the candidate. Traverse the array — increment votes if the element matches the candidate, otherwise decrement. If votes reach zero, update the candidate. The last candidate standing is the majority element. 🔹 Time Complexity: O(n) — only one traversal through the array. 🔹 Space Complexity: O(1) — uses constant extra space. 🔹 Key Learnings: Learned how voting logic simplifies counting-heavy problems. Achieved 99.76% faster runtime on LeetCode. Reinforced how simplicity and logic often outperform brute force. 💡 Every dataset has a voice — you just need the right logic to hear it. #100DaysOfCode #LeetCode #Java #ProblemSolving #DSA #CodingChallenge #BoyerMooreAlgorithm
To view or add a comment, sign in
-
-
🗓 Day 8/ 100 – #100DaysOfLeetCode 📌 Problem 3234: Count the Number of Substrings With Dominant Ones A substring is said to have dominant ones if: 👉 #1s ≥ (#0s)² The task is to count how many substrings in the binary string satisfy this condition. 🧠 My Approach: 🔹 Iterated through substrings while maintaining counts of zeros and ones. 🔹 Used the condition ones ≥ zeros² to determine whether a substring is valid. 🔹 Applied early stopping when the zero count became too large, since the quadratic requirement makes dominance increasingly difficult to achieve. 🔹 This pruning significantly reduced unnecessary checks and improved the overall efficiency. ⏱ Time & Space Complexity Time Complexity: O(n · √n) Because for each starting index, we only explore substrings until the zero count reaches ~√n (beyond which zeros² becomes too large to satisfy). This is a major improvement over the brute-force O(n²). Space Complexity: O(1) Only uses a few counters (ones, zeros, indices). 💡 Key Learning: This problem beautifully shows how mathematical constraints can simplify substring evaluation. Recognizing that zeros affect the condition quadratically helped guide a smarter pruning strategy, turning an expensive brute-force check into something efficient and elegant. #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
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