Finding the Ultimate Peak in a Tree - Day 210 Today Today I worked on a complex tree problem which is LeetCode 124 Binary Tree Maximum Path Sum. This problem is challenging because the path can start and end at any node in the tree and it does not have to pass through the root. I used a recursive strategy to solve this efficiently. At every node, I calculated the maximum contribution from the left side and the right side. A very important part of the logic was using zero if the sum from a child was negative. This means we only include a branch if it actually adds value to our total sum. If it is negative, we just ignore that branch. At each node, I updated a global variable to keep track of the highest sum found so far. I calculated this by adding the current node value to the sums of both its left and right sides. This allowed me to check paths that curve through the current node. For the recursive step, I returned the current node value plus only the better of the two sides. I did this because a single path cannot split in two different directions as it continues up to a parent node. This problem was a perfect way to practice how recursion can manage local calculations while updating a global maximum result. #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #BinaryTree #Recursion #AlgorithmDesign #ProblemSolving #DataStructures #SoftwareEngineering #CodingJourney #LogicBuilding #TechSkills #WebDevelopment #ProgrammingPractice #CleanCode #DailyProgress #JavaScriptDeveloper #CodingChallenge #TechnicalInterview
Maximizing Binary Tree Path Sum with Recursion
More Relevant Posts
-
Day 82 - LeetCode Journey 🚀 Solved LeetCode 92: Reverse Linked List II (Medium) — a powerful problem that takes basic reversal to the next level. We already know how to reverse an entire linked list. But here, the challenge is to reverse only a specific portion — between positions left and right — while keeping the rest intact. 💡 Core Idea (Partial Reversal + Pointer Rewiring): Use a dummy node to simplify edge cases Move a pointer (prev) to the node just before position left Start reversing nodes one by one within the given range Reconnect the reversed sublist back to the original list This is done using in-place pointer manipulation. 🤯 Why it works? Because instead of reversing the entire list, we carefully rewire only the required segment, preserving connections before and after the range. ⚡ Key Learning Points: • Partial reversal of linked list • Advanced pointer manipulation • Importance of dummy node in edge cases • In-place modification without extra space • Maintaining O(n) time and O(1) space This problem is a big step up from basic linked list reversal. Also, this pattern connects with: Reverse Linked List (full reversal) Reverse Nodes in k-Group Reorder List Palindrome Linked List ✅ Better control over pointer operations ✅ Strong understanding of in-place transformations ✅ Confidence with medium-level linked list problems From full reversal to selective reversal — this is real progress 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
Day 79 - LeetCode Journey 🚀 Solved LeetCode 203: Remove Linked List Elements (Easy) — a deceptively simple problem that strengthens core linked list fundamentals. At first, it feels like just removing nodes with a given value. But the real challenge lies in handling edge cases cleanly, especially when deletions happen at the head or consecutively. 💡 Core Idea (Dummy Node + Pointer Control): Introduce a dummy node pointing to head Use a pointer (prev) to traverse the list If prev.next.val == target, skip the node Otherwise, move the pointer forward This ensures safe deletion without losing track of the list. 🤯 Why it works? Because the dummy node acts as a stable anchor, allowing uniform handling of all cases — including when the head itself needs to be removed. ⚡ Key Learning Points: • Importance of dummy node in linked list problems • Handling edge cases like head deletion • Managing consecutive deletions efficiently • Clean pointer manipulation without breaking links • Achieving O(n) time and O(1) space This problem builds the foundation for many advanced linked list operations. Also, this pattern connects with: <>Remove Nth Node from End <>Delete Node in Linked List <>Remove Duplicates (I & II) <>Partition List ✅ Stronger understanding of pointer-based logic ✅ Better handling of tricky edge cases ✅ Writing clean and robust linked list code Mastering these basics is what makes complex problems easier later 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
Day 29/30 – LeetCode streak Problem: Fancy Sequence You need to support 'append', 'addAll', 'multAll', and 'getIndex' under modulo '(10^9 + 7)' in 'O(1)' per operation. Core idea Keep the logical sequence implicitly via a global affine transform: * Store an internal array 'vals[]'. * Maintain global coefficients 'mul = a' and 'add = b' so that for every index 'i': 'real_i ≡ a · vals[i] + b (mod M)' * Initially, 'a = 1' and 'b = 0', so the stored value equals the real value. Operations * 'append(val)' We want to store a value 'x' such that: 'a · x + b ≡ val (mod M)' Rearranging gives: 'x ≡ (val − b) · a⁻¹ (mod M)' Since 'M' is prime and 'a ≠ 0', the modular inverse 'a⁻¹' exists and can be computed using Fermat’s little theorem. * 'addAll(inc)' Adding a constant to every element changes the transform: 'a · x + b → a · x + (b + inc)' So we simply update: 'add = (add + inc) % MOD'. * 'multAll(m)' Multiplying every element scales both coefficients: 'a · x + b → (a · m) · x + (b · m)' So update: 'mul = (mul * m) % MOD' 'add = (add * m) % MOD'. * 'getIndex(idx)' If the index is out of range return '-1'. Otherwise compute the real value using the stored transform: 'real = (mul * vals[idx] + add) % MOD'. Day 29 takeaway: Instead of updating every element on each operation, using a lazy affine transformation 'a · x + b' lets you represent the entire sequence with just two parameters, turning what would normally be 'O(n)' updates into constant-time operations. #leetcode #dsa #java #math #design #consistency
To view or add a comment, sign in
-
-
🚀 Day 13/100 – LeetCode DSA Challenge 🔹 Problem Solved: 238. Product of Array Except Self Today’s problem was a great exercise in array manipulation and optimization. 📌 Problem Summary: Given an array nums, return a new array where each element is the product of all elements except itself. 📊 Example: Input: [1,2,3,4] Output: [24,12,8,6] 💡 What I Learned: How to handle edge cases like zeros in an array Importance of time complexity O(n) Why some solutions (like division) are not always valid Concept of prefix & suffix products (optimal approach) ⚠️ Challenge: Cannot use division Must solve in linear time 🧠 My Approach: First tried using total product and division Faced issues with zero values (division by zero error) Improved the logic by handling zero cases carefully 🔥 Key Insight: If there is: More than 1 zero → all outputs = 0 Exactly 1 zero → only that index gets product No zero → normal calculation works 📈 Next Goal: Learn and implement the optimal solution without division (prefix + suffix method) #Day13 #100DaysOfCode #LeetCode #DSA #Java #CodingJourney #ProblemSolving #FutureDeveloper
To view or add a comment, sign in
-
-
Solved LeetCode Medium – 1536. Minimum Swaps to Arrange a Binary Grid today! 💻 Instead of actually swapping rows in the grid, I optimized the solution by tracking trailing zero counts per row and performing swaps on that array. This significantly simplifies the implementation and improves readability. Approach I Followed 1. Count Trailing Zeroes in Each Row For each row in the grid, traverse from the rightmost column. Count how many continuous zeroes appear at the end of that row. Store these counts in an array zeroes[i]. Example: Row: [1,0,0,0] → trailing zeroes = 3 Row: [1,1,0,0] → trailing zeroes = 2 2. Determine Required Zeroes per Row For row i, we need at least: requiredZeroes = n - i - 1 Because every row above must have enough zeros so that all elements above the main diagonal are zero. 3. Find a Suitable Row Search for the first row j ≥ i that has enough trailing zeroes. If no such row exists → return -1 (arrangement impossible). 4. Bring That Row Up Using Adjacent Swaps Swap row j upward until it reaches position i. Each adjacent swap increases the swap count. Instead of swapping rows in the grid, swap values in the zeroes array. This simulates the required row movement efficiently. 5. Continue Until Grid is Valid Repeat for every row until all constraints are satisfied. ✅ Time Complexity: O(n²) ✅ Space Complexity: O(n) It was a great exercise in greedy thinking, array manipulation, and edge-case handling. Always satisfying to break down a tricky grid problem into a simpler representation! 🚀 #LeetCode #DSA #Java #CodingPractice #GreedyAlgorithm #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
Priority Order in JavaScript Day 216 Today Today I learned about the Priority Queue. It is a very important concept in data structures. In a normal queue the rule is first in first out. But in a priority queue the element with the highest priority is processed first. Think of a hospital emergency room. A patient with a serious injury gets treated before someone with a cold even if the person with the cold arrived earlier. This is exactly how a priority queue works. I learned that there are two ways to implement this. You can use an array and sort it every time but that is slow. The best way is using a Heap. Using a Heap makes adding and removing elements very fast because the time complexity is log n. JavaScript does not have a built in priority queue like some other languages. This means we have to build it ourselves using classes. This is a great way to practice logic building and understand how things work under the hood. A very helpful tip for interviews is that if a question asks for the Kth smallest or Kth largest element you should think of using a priority queue or a heap. It makes the solution much more efficient. Today I solved these LeetCode questions: 215 Kth Largest Element in an Array 703 Kth Largest Element in a Stream #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #DataStructures #PriorityQueue #CodingInterview #ProgrammingDaily #SoftwareEngineering #TechLearning #WebDevelopment #LogicBuilding #ProblemSolving #JavaScriptDev #JSCode #ArrayLogic #HeapDataStructure #AlgorithmDesign #CodingChallenge #BinaryHeap
To view or add a comment, sign in
-
Day 32 of #75DaysofLeetCode 🚀 LeetCode 2130 – Maximum Twin Sum of a Linked List Another day, another clean Linked List trick 💡 🔍 Problem Insight: In a linked list of even length, each node has a twin: First ↔ Last Second ↔ Second Last …and so on We need to find the maximum twin sum. 🧠 Key Idea (Interview-Ready Approach): Instead of using extra space, we: 1️⃣ Find the middle of the list (slow & fast pointers) 2️⃣ Reverse the second half 3️⃣ Traverse both halves and compute the twin sums ⚡ Why this approach? ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(1) (No extra memory!) 💯 Clean and optimal solution 📌 Example: Input: 1 → 2 → 3 → 4 Twin sums: (1+4)=5, (2+3)=5 👉 Output: 5 🔥 Takeaway: This problem is a perfect example of combining: Two pointers In-place reversal Space optimization 💬 Have you solved this using a different approach? Let’s discuss below 👇 #LeetCode #DataStructures #LinkedList #Java #CodingInterview #ProblemSolving
To view or add a comment, sign in
-
-
Moving Nodes and Building Order - Day 213 Today Today I learned how to actually build a Min Heap from scratch using JavaScript. Yesterday was about the structure but today was about the movement of data. When I insert a new value I always put it at the very end of the array. Then I compare it with its parent. If the new value is smaller I swap them. I keep doing this until the value finds its right place. This is called heapify up or bubbling up. Deleting the smallest value is different. The smallest value is always at the top root. I take it out and move the last value of the array to the root. Since this value is probably too large I move it down by comparing it with its children. I always swap with the smaller child to keep the min heap property. This is called heapify down. I used a JavaScript class to manage this. I used simple math formulas to find the connections between parents and children in the array. This way I do not need complex pointers. Today was about logic and writing clean helper functions to make the heap work. LeetCode logic and structures solved today: Manual implementation of Min Heap class Logic for Heapify Up insertion Logic for Heapify Down deletion Array index mapping for binary trees #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #DataStructures #MinHeap #AlgorithmBuilding #LogicDevelopment #ProgrammingDaily #SoftwareEngineer #CodingLogic #JavaScriptDeveloper #Heapify #ArrayLogic #ProblemSolving #CodePractice #TechLearning #StructureAndLogic #BuildingBlocks #WebDevLearning
To view or add a comment, sign in
-
🔥 Day 59/100 – LeetCode Challenge 📌 Problem Solved: Remove Duplicates from Sorted Array II (Medium) Today’s problem was a great exercise in in-place array manipulation and two-pointer technique. 💡 Key Idea: Since the array is already sorted, duplicates are adjacent. Instead of removing all duplicates, we allow each element to appear at most twice. 👉 The trick is to compare the current element with the element at index k-2. If they are the same → skip ❌ If different → keep it ✅ ⚙️ Approach: Initialize pointer k = 2 Traverse from index 2 Copy valid elements forward Maintain order without extra space 🧠 What I learned: How to efficiently handle constraints like “at most twice” Importance of thinking in terms of index relationships (k-2) Writing optimal O(n) solutions with O(1) space 📊 Performance: ⚡ Runtime: 0 ms (100%) 💾 Memory: 48.46 MB 💻 Tech Used: Java Consistency is key 🔑 — 59 days done, 41 more to go! #100DaysOfCode #LeetCode #Java #DataStructures #CodingChallenge #ProblemSolving #TechJourney
To view or add a comment, sign in
-
-
Day 77 - LeetCode Journey Solved LeetCode 82: Remove Duplicates from Sorted List II (Medium) today — a more advanced version of the duplicate removal problem. Unlike the basic version, here we need to remove all nodes that have duplicates, leaving only distinct values. 💡 Core Idea: Use a dummy node + two pointers approach. • A dummy node helps handle edge cases (like duplicates at the head) • Use prev to track the last confirmed unique node • Use curr to traverse the list When duplicates are found: → Skip all nodes with that value → Connect prev.next to the next distinct node If no duplicate: → Simply move prev forward ⚡ Key Learning Points: • Importance of a dummy node in linked list problems • Handling edge cases at the head • Removing elements completely (not just skipping extras) • Clean pointer manipulation with O(n) time and O(1) space This problem highlights the difference between: Keeping one copy (Easy version) Removing all duplicates (Medium version) That small change makes the logic significantly more interesting. ✅ Stronger understanding of pointer control ✅ Better handling of edge cases ✅ Improved problem-solving depth in linked lists These variations are where real learning happens 🚀 #LeetCode #DSA #Java #LinkedList #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
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