🚀 Just Solved LeetCode #124 — Binary Tree Maximum Path Sum 📘 Problem: Given the root of a binary tree, return the maximum path sum of any non-empty path. A path can start and end at any node, and it’s the sum of all node values along that path. Example: Input → [1,2,3] Output → 6 Explanation → The optimal path is 2 → 1 → 3 with a sum of 6. 🧠 My Approach: I used a recursive DFS (Depth First Search) to calculate the maximum gain from each node: 1️⃣ For each node, calculate the maximum path sum including its left and right subtrees. 2️⃣ Compare the sum of the current path with the global maximum (`maxSum`). 3️⃣ Return the max gain that can be extended to the parent node (node value + max of left/right gain). 4️⃣ Used `Math.max()` to ensure negative paths don’t reduce the result. 💡 What I Learned: ✅ Importance of returning gain vs total path sum in recursive tree problems ✅ How to handle global state (`maxSum`) in recursion ✅ Deepened understanding of DFS-based tree traversal and dynamic recursion logic #LeetCode #Java #DSA #BinaryTree #CodingJourney
Solved LeetCode #124: Binary Tree Maximum Path Sum with DFS
More Relevant Posts
-
🗓 Day 7 / 100 – #100DaysOfLeetCode 🔢 Problem 2536: Increment Submatrices by One Today’s challenge involved processing multiple submatrix increment queries on an n x n matrix, initially filled with zeros. 🧠 My Approach Instead of updating every cell inside each submatrix (which would be too slow for up to 10⁴ queries), I used a row-wise difference array technique. For each query [r1, c1, r2, c2]: Increment prefix[row][c1] Decrement prefix[row][c2+1] (if within bounds) This allows efficient marking of increments. Later, prefix-summing each row reconstructs the final matrix. ⏱ Time Complexity O(q × n) where q = number of queries (We touch r2 - r1 + 1 rows per query) 💾 Space Complexity O(n²) for the prefix matrix #LeetCode #Java #ProblemSolving #CodingChallenge #100DaysOfCode #DSA #LearningEveryday
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 73 String Manipulation Problem: Valid Anagram (LeetCode #242) Task: Given two strings s and t, return true if t is an anagram of s, otherwise false. Example: Input: s = "anagram", t = "nagaram" → Output: true Input: s = "rat", t = "car" → Output: false My Approach:- Method 1 – Sorting Converted both strings into character arrays. Sorted them and compared if equal, they’re anagrams! Time Complexity: O(n log n) Method 2 – Frequency Count (Optimized) Counted occurrences of each character in s and t. If every count matches, it’s a valid anagram. Time Complexity: O(n) | Space: O(1) String problems may look simple, but optimizing from sorting to counting makes a huge difference. Small logic shifts often lead to big performance gains! #100DaysOfCode #Java #ProblemSolving #LeetCode #CodingJourney #takeUforward #DataStructures #Algorithms #StringManipulation #GeeksForGeeks #CodeNewbie
To view or add a comment, sign in
-
-
📌 Day 38/100 – Make array elements equal to zero (LeetCode 3354) 🔹 Problem: Given an integer array nums, each element can be a number or zero. You need to find how many zeros in the array can be replaced by either +1 or -1 such that the total sum on both sides of that zero (left and right) remains balanced or differs by 1. 🔹 Approach: First, calculate the total sum s of all elements. Maintain a prefix sum l as you iterate. For each zero: If l * 2 == s, both +1 and -1 replacements are valid → add 2 to ans. If |l * 2 - s| == 1, only one replacement is valid → add 1 to ans. Return the total count ans. 🔹 Key Learning: Prefix sums simplify balance-based problems. Comparing 2 * prefixSum with total sum helps quickly check left-right equilibrium. 🔹 Complexity: Time: O(n) — single pass through array Space: O(1) — no extra storage used 🔹 Hashtags: #Day38Of100 #LeetCode3354 #100DaysOfCode #Java #DSA #ProblemSolving #PrefixSum #CodingChallenge
To view or add a comment, sign in
-
-
🔹 Day 47: Find Pivot Index (LeetCode #724) 📌 Problem Statement: Given an array of integers nums, the pivot index is the index where the sum of all numbers to the left is equal to the sum of all numbers to the right. If no such index exists, return -1. If multiple exist, return the leftmost one. ✅ My Approach: I first calculated the total sum of the array, then iterated through each element keeping track of the left sum. At each index, I checked whether left sum == total sum - left sum - current element. If true, that index is the pivot index. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 0 ms (Beats 100%) Memory: 45.41 MB (Beats 66.27%) 💡 Reflection: This problem strengthened my understanding of prefix sums and efficient single-pass array traversal. A clean and optimized logic! 💪 #LeetCode #Java #Arrays #PrefixSum #100DaysOfCode #Day47
To view or add a comment, sign in
-
-
🚀 Just Solved LeetCode #102 — Binary Tree Level Order Traversal 📘 Problem: Given the root of a binary tree, return the level order traversal of its nodes' values — meaning, traverse the tree level by level from left to right. Example: Input → [3,9,20,null,null,15,7] Output → [[3], [9,20], [15,7]] 🧠 My Approach: I solved this using a recursive approach instead of the usual queue-based BFS. 1️⃣ First, I calculated the total number of levels in the tree using recursion. 2️⃣ Then, for each level, I called a helper function `nThLevel()` to collect all nodes at that level. 3️⃣ I stored each level’s nodes in a separate list and finally returned a list of lists as the result. This approach helped me deeply understand the relationship between recursion depth and tree levels. 💡 What I Learned: ✅ Different ways to perform level order traversal — BFS vs recursion. ✅ How to effectively use recursion to explore each tree level. ✅ Improved understanding of function calls, base conditions, and data storage in recursive algorithms. #LeetCode #Java #DSA #BinaryTree #CodingJourney
To view or add a comment, sign in
-
-
🚀Day 42/100 - Problem of the day :- Count the Number of Substrings With Dominant Ones. 🎯 Goal:- Solved another interesting LeetCode problem and improved my understanding of prefix-based logic for substring counting. 💡 Core Idea:- The approach uses a prefix tracking array to store the last seen index of '0'. Using this information, we efficiently compute the number of valid substrings ending at each position—without re-checking previous characters. 📌 Key Takeaway:- Efficient solutions come from observing patterns in the input string and leveraging previously computed states. This helps reduce repetitive work and significantly improves performance. 🧠 Time Complexity:- O(n) — We traverse the string once and compute results in a single pass. 💾 Space Complexity:- O(n) — For storing prefix array to track last valid index. #100DaysChallenge #Java #DSA #Day42 #CodingJourney #ProblemSolving #Leetcode
To view or add a comment, sign in
-
-
🚀#PostLog34 🔹 LeetCode 1901: Find a Peak Element II Problem was focused on efficiently finding a peak element in a 2D grid — one that’s greater than all its adjacent cells (top, bottom, left, and right). 💡 Concept learned: Instead of scanning the entire grid, a binary search on columns helps reduce time complexity to O(m log n). For each middle column, find the global maximum element, then decide which side to move based on neighboring values — simple yet powerful divide-and-conquer logic. ✅ 58/58 test cases passed ⚡ Runtime: 0ms | Beats 100% of Java submissions Each problem reinforces how algorithmic thinking and optimization go hand-in-hand — step by step toward sharper logic and cleaner solutions. #LeetCode #Java #DSA #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 9 of 100 Days of LeetCode 🧩 Problem: #242. Valid Anagram 💻 Difficulty: Easy 🔍 Concept: Check whether two strings are anagrams — i.e., they contain the same characters in the same frequency, just rearranged. ⚙️ Approach Used: Used a frequency array of size 26 to count occurrences of each character in the first string. Decreased counts while scanning the second string. If all frequencies end up zero ➜ both strings are anagrams ✅ 🧠 Key Learnings: Practiced frequency array patterns for string problems. Learned to avoid sorting-based solutions for better time complexity (O(n) instead of O(n log n)). 💻 Code (Java): class Solution { public boolean isAnagram(String s, String t) { int[] freq = new int[26]; for (char c : s.toCharArray()) freq[c - 'a']++; for (char c : t.toCharArray()) freq[c - 'a']--; for (int f : freq) if (f != 0) return false; return true; } } 💬 Reflection: Small wins count too! Even the simplest problems help in strengthening your logical foundation and pattern recognition. #100DaysOfLeetCode #Day9 #ProblemSolving #Java #LeetCode #DSA #CodingChallenge #LearningEveryday
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
-
-
💻 LeetCode Daily Challenge - #3217. Delete Nodes From Linked List Present in Array ❓ Problem statement: You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums. 🧠 Intuition: While traversing linked list, We need to find out if a element is present in nums array efficiently. Add all nums to a SET so we can have constant lookup time to finding if a number is in nums. ⚙️ Approach: 1. Create a hashset to store elements of nums array. 2. We might have to remove the head element so make a dummy node whose next node is head. 3. Make two nodes prev which points to dummy node & curr which points to head. 4. Traverse linked list until curr becomes null -> If curr node value is in the set of nums remove it by setting next node of prev to curr's next. 5. Return dummy node's next node. ⏳ Time Complexity: O(n + m) -> n: size of nums array, m: size of linked list. 📦 Space complexity: O(n) -> HashSet of size n Github: https://lnkd.in/gRbRrJ5P #Java #DSA #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
More from this author
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
Keep Shining ✨