🚀 Binary Tree Maximum Path Sum 🌳🧠 Just completed LeetCode – Binary Tree Maximum Path Sum, one of the classic Hard problems that truly tests your understanding of tree DFS + recursion + dynamic programming concepts. 🔍 Key Learnings: A path can start and end at any node (not necessarily the root). At each node, we must consider three possibilities: Path passing through the node (left + node + right) Path extending from one side only (to be returned to parent) Path consisting of the node alone (important for negative values) Maintained a global maximum to track the best path sum seen so far. 🧠 Core Insight: The value returned to the parent must be a single-sided path The global answer may include both children, but cannot be extended upward ⚙️ Complexity: Time: O(n) — each node visited once Space: O(h) — recursion stack (h = tree height) This problem significantly strengthened my understanding of: DFS traversal patterns Handling negative values in trees Separating global answers from recursive return values #LeetCode #DSA #BinaryTree #DynamicProgramming #Recursion #Java #ProblemSolving #CodingJourney #SoftwareEngineering #LearningByDoing
Binary Tree Maximum Path Sum LeetCode Solution
More Relevant Posts
-
🚀 Day 47 | LeetCode Medium 🟩 Set Matrix Zeroes Today’s problem focused on matrix traversal + space trade-offs, and it was a great reminder that clarity beats complexity. 🧠 Core Idea If any cell in the matrix is 0, then its entire row and column must be set to 0. Instead of modifying the matrix immediately (which can break logic), I used an auxiliary tracking approach. 🛠️ Approach Used Traverse the matrix once Mark affected rows and columns using helper arrays Traverse again and update cells based on these markers This avoids incorrect cascading zeros and keeps the logic clean. ⚡ Why this works Separation of detection and update No accidental overwrites Easy to reason and debug ⏱️ Complexity Time: O(m × n) Space: O(m + n) 🔗 Code on GitHub 👉 https://lnkd.in/g-zxCztf 💡 Key Learning In matrix problems, when you update is just as important as what you update. 🔥 Consistency > Speed Another step forward in my daily DSA journey 🚀 #LeetCode #LeetCodeDailyProblem #SetMatrixZeroes #DSA #Java #Arrays #Matrix #ProblemSolving #CodingJourney #100DaysOfCode #TechCommunity
To view or add a comment, sign in
-
-
🚀 LeetCode Milestone: Problem #1448 – Count Good Nodes in Binary Tree (Medium) Today I solved another interesting binary tree problem that sharpened my DFS (Depth-First Search) skills. 🔹 Problem Statement: A node in a binary tree is considered good if, along the path from the root to that node, there are no values greater than the node itself. The task is to count all such good nodes. 🔹 Key Insight: Use DFS traversal. Track the maximum value seen so far along the path. If the current node’s value is greater than or equal to this maximum, it’s a good node. Update the maximum as we go deeper. 🔹 Example: Input: [3,1,4,3,null,1,5] Output: 4 Explanation: Nodes (3, 4, 5, 3) are good. 🔹 Learning: This problem reinforced the importance of carrying state (like max-so-far) during recursion. It’s a neat example of how DFS can elegantly solve path-dependent conditions in trees. 💡 Every solved problem adds confidence and clarity to my coding journey. Looking forward to tackling more challenging problems and sharing my progress! #LeetCode #CodingInterview #Java #DSA #BinaryTree #ProblemSolving #BackendDeveloperJourney
To view or add a comment, sign in
-
-
🚀 Day 50 of #100DaysOfCode 🎯 (Halfway there! 🔥) Today’s challenge was an array + dynamic programming twist problem — 📊 LeetCode: Maximum Product Subarray 📌 Problem Summary Given an integer array, find the contiguous subarray (containing at least one number) that has the largest product. At first glance, it looks similar to maximum subarray sum… but the presence of negative numbers changes everything ⚠️ 🧠 My Approach: Tracking Max & Min Products The key insight 👇 A negative number can turn the smallest product into the largest. So instead of tracking only the maximum, I tracked: ✅ max product ending at current index ✅ min product ending at current index At each step: Compute new max using (current, max*current, min*current) Compute new min similarly Update the global result This keeps everything in one pass 🚀 ⚙️ Complexity Analysis ⏱ Time: O(n) 💾 Space: O(1) Efficient and clean ✨ 🔥 Key Learning Negative numbers can flip the problem logic Some DP problems don’t need arrays — just smart state tracking Always think in terms of states, not just values ✅ Solution accepted with strong runtime performance Another powerful array pattern mastered 💪 Onward from Day 50 — the grind continues 🚀🔥 #100DaysOfCode #LeetCode #Java #DynamicProgramming #Arrays #ProblemSolving #CodingJourney #DSA
To view or add a comment, sign in
-
-
🚀 Day 90/100 - Problem of the day :- Number of Ways to Paint N x 3 Grid. 🎯 Goal Efficiently compute the total number of valid ways using dynamic programming with modular arithmetic. 💡 Core Idea Use DP with two state arrays to build results iteratively, applying recurrence relations and modulo to handle large values. 🔑 Key Takeaway Breaking a problem into well-defined states makes complex counting problems manageable and scalable. 📦 Space Complexity: O(n) ⏱️ Time Complexity: O(n) #LeetCode #DynamicProgramming #Java #ProblemSolving #DSA #CodingJourney #Consistency #100DaysChallenge
To view or add a comment, sign in
-
-
🔹 Day 93 – LeetCode Practice 📌 Problem: Find the Difference (LeetCode #389) 📊 Difficulty: Easy 🧠 Problem Overview: You’re given two strings s and t, where t is formed by shuffling s and adding one extra character. The task is to identify and return that added character. ✅ My Approach: Calculated the total character values of both strings. Compared the difference between them to determine the extra character added to the second string. This approach avoids additional data structures and keeps the solution simple and efficient. 📈 Complexity Analysis: Time Complexity: O(n) Space Complexity: O(1) 🚀 Submission Results: Status: Accepted ✅ Runtime: 3 ms (Beats 40.50%) Memory: 43.14 MB (Beats 55.56%) 💡 Reflection: This problem shows how mathematical reasoning can simplify string manipulation tasks. A neat reminder that elegant solutions don’t always require complex logic. #LeetCode #DSA #Strings #Java #ProblemSolving #CodingPractice #Learning
To view or add a comment, sign in
-
-
🚀 Day 488 of #500DaysOfCode 📌 LeetCode Problem: 2976. Minimum Cost to Convert String I Today’s challenge was about minimizing the cost to convert one string into another using a set of given character transformation rules — each with an associated cost. 💡 Key Idea: Model this as a graph problem where each lowercase character is a node, and every transformation is a directed edge with a cost. Then use Floyd–Warshall to compute the minimum conversion cost between all pairs of characters. 🔍 Approach Summary: ✔ Build a 26×26 cost matrix for all character conversions ✔ Use Floyd–Warshall to find the cheapest paths ✔ For each position in the string, sum the cost of converting source[i] → target[i] ✔ Return the total cost — or -1 if impossible ⚙️ Time Complexity: 26³ for preprocessing + O(n) for string traversal, which is efficient even for large inputs. 💬 What I learned today: Graph applications go beyond nodes and edges — even string transformations can be mapped beautifully as a shortest path problem! 🔁 Keep coding. Keep growing. #java #leetcode #codingchallenge #graphalgorithms #floydwarshall
To view or add a comment, sign in
-
-
🚀 Day 97/100 - Problem of the day :- Miniy ASCII Delete Sum for Two Strings. 🎯 Goal Find the minimum ASCII delete sum to make two strings equal. 💡 Core Idea Use Dynamic Programming to compute the maximum ASCII sum of the Longest Common Subsequence (LCS). Answer = (Total ASCII of both strings) − 2 × (LCS ASCII sum). 📌 Key Takeaway •Sometimes minimizing cost = maximizing what you keep. •Transforming problems smartly (Min → Max) simplifies the solution. 📄 Space Complexity : O(n × m) — DP table of two strings. ⏱️ Time Complexity : O(n × m) — Filling the DP matrix. #DSA #DynamicProgramming #LeetCode #Java #CodingJourney #ProblemSolving #Algorithms #TechSkills #100DaysChallenge
To view or add a comment, sign in
-
-
🌳 LeetCode 104. Maximum Depth of Binary Tree – Solved! Today was special because I not only solved this problem but also learned a new concept: Binary Trees. This problem asks us to determine the maximum depth of a binary tree, i.e., the longest path from the root to the farthest leaf. 🔎 My Process: Step 1: Identify the base case → If the node is null, depth = 0. Step 2: Break down the problem → For each node, calculate the depth of its left and right subtrees. Step 3: Combine results → Take the maximum of both subtree depths. Step 4: Add the current node → Add 1 to represent the current level. 💡 Key Takeaways: Recursion is a natural fit for tree problems, as it simplifies complex structures into smaller subproblems. This approach ensures all paths are explored and the longest one is returned. Strengthened my confidence in binary tree traversal and recursive problem-solving. This adds to my journey of solving 100+ LeetCode problems, each sharpening my DSA skills and preparing me for real-world backend challenges. 🚀 #LeetCode #DSA #BinaryTree #ProblemSolving #CodingJourney #Java
To view or add a comment, sign in
-
-
Day 18 / 50 – LeetCode Challenge Find Kth Missing Positive Number Problem Description: You are given a sorted array of distinct positive integers arr and an integer k. The objective is to determine the k-th missing positive integer that does not appear in the array. Conceptual Insight: For any index i in the array, if no numbers were missing, the value should ideally be i + 1. Therefore, the number of missing positive integers up to index i is calculated as: ini Copy code missing = arr[i] − (i + 1) This observation enables an efficient binary search–based solution. Algorithm (Binary Search Approach): Initialize two pointers: low = 0 and high = n − 1. Perform binary search on the array: Compute mid. Calculate the count of missing numbers up to mid. If the missing count is less than k, shift the search to the right. Otherwise, shift the search to the left. After termination, the k-th missing number is computed as: k + (high + 1) // equivalent to k + low Complexity Analysis: Time Complexity: O(log n) Space Complexity: O(1) #Day18 #LeetCode #50DaysOfLeetCode #BinarySearch #DataStructures #Algorithms #Java #ProblemSolving #CodingPractice #TechnicalInterview #DSA #CompetitiveProgramming
To view or add a comment, sign in
-
-
Day 3: The Reality of the "Hard" Label. 🧠 Today was a humbling reminder that growth isn't always a straight line. I tackled LeetCode #1411 (Number of Ways to Paint N × 3 Grid), and it took me the entire day to truly grasp the logic. As a beginner in Dynamic Programming, I faced multiple failed attempts and head-scratching moments. But after internalizing the state transitions, I finally got that "Accepted" screen. The Challenge: Find the number of ways to paint an n*3 grid using 3 colors such that no two adjacent cells have the same color. My Approach (State-Space DP): State Generation: First, I generated all possible valid configurations for a single row (out of 27 combinations, only 12 are valid). Adjacency Map: I built a neighbours list to determine which row configurations can follow each other without breaking the color constraints. Memoization: Used a recursive solve function with a memo table to store results of subproblems and avoid redundant calculations. Handling Large Numbers: Used long and MOD (10^9 + 7) to prevent integer overflow. Complexity: Time: O(n * S^2) where S is the number of valid states (12). Space: O(n * S) for the memoization table. It’s currently a "brute-force" DP approach, and I know there are further mathematical optimizations (O(log n)), but today was about understanding the concept over the shortcut. I'll be back to optimize this once my DP foundation is stronger! 📂 GitHub Repo: https://lnkd.in/g-RMsp6a If you're also struggling with DP, keep pushing. The "aha!" moment is worth the struggle. #Java #DynamicProgramming #LeetCode #BuildingInPublic #SoftwareEngineering #JadavpurUniversity #100DaysOfCode
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