🌲 Day 38/75: Measuring the Diameter of a Binary Tree! Today’s LeetCode challenge was a step up in complexity: finding the Diameter of a Binary Tree. The diameter is the length of the longest path between any two nodes in a tree, which may or may not pass through the root. The Strategy: This problem is tricky because the longest path isn't always just the height of the left side plus the height of the right side at the root. It could be tucked away in one of the subtrees! I used a recursive Depth-First Search (DFS) that performs two tasks at once: Calculates Height: It returns the height of the current subtree to its parent. Updates Diameter: It calculates the path passing through the current node (leftHeight + rightHeight) and updates a global diameter variable if this path is the longest found so far. Performance: ✅ Runtime: 1 ms ✅ Complexity: $O(n)$ Time | $O(h)$ Space It’s a great example of how to extract multiple pieces of information from a single recursive pass. One more day closer to the 40-day mark! 🚀 #LeetCode #75DaysOfCode #Java #BinaryTree #Recursion #Algorithms #DataStructures #TechJourney
Calculating Binary Tree Diameter with DFS in Java
More Relevant Posts
-
📌 Median of Two Sorted Arrays Platform: LeetCode #4 Difficulty: Hard ⚙️ Approach • Apply binary search on the smaller array for efficiency • Define search space from 0 to n1 • Partition both arrays such that: – Left half contains (n1 + n2 + 1) / 2 elements – Right half contains remaining elements • Identify boundary elements: – l1, l2 → left side elements – r1, r2 → right side elements • Check valid partition: – l1 <= r2 and l2 <= r1 • If valid: – For even length → median = average of max(left) and min(right) – For odd length → median = max(left) • If not valid: – If l1 > r2, move left – Else move right 🧠 Logic Used • Binary Search on partition index • Dividing arrays into balanced halves • Handling edge cases using boundary values • Achieving optimal O(log(min(n1, n2))) time complexity 🔗 GitHub: https://lnkd.in/g_3x55n8 ✅ Day 36 Completed – Revised advanced binary search and partition-based problem. #100DaysOfCode #Java #DSA #ProblemSolving #CodingJourney #Algorithms #DataStructures #LeetCode #CodingPractice #CodeEveryDay #BinarySearch #ArrayProblems
To view or add a comment, sign in
-
-
🚀 LeetCode Problem Solved: Peak Index in a Mountain Array (#852) Today I solved the Peak Index in a Mountain Array problem using an optimized Binary Search approach. 💡 Approach: Instead of using a brute-force linear scan, I applied Binary Search to reduce the search space: Compare the middle element with its neighbors. If it's greater than both → it's the peak. If the sequence is increasing → move right. If decreasing → move left. ⚡ Time Complexity: O(log n) ⚡ Space Complexity: O(1) 📈 Performance: ✅ Runtime: 0 ms (Beats 100%) ✅ Efficient and scalable solution Consistency in problem-solving is the real game changer 💪 #LeetCode #DataStructures #Algorithms #BinarySearch #CodingJourney #Java #ProblemSolving
To view or add a comment, sign in
-
-
🚀 Day 565 of #750DaysOfCode 🚀 🔍 Problem Solved: Minimum Absolute Distance Between Mirror Pairs Today’s problem was all about identifying mirror pairs in an array — where reversing one number equals another — and finding the minimum index distance between such pairs. 💡 Key Insight: Instead of brute force (O(n²)), we can optimize using a HashMap to track previously seen reversed values. 🧠 Approach: Traverse the array once For each number: Check if it already exists in the map → update minimum distance Compute its reverse Store the reversed number with its index Return the minimum distance, or -1 if no pair exists 📊 Complexity: Time: O(n × d) → d = number of digits Space: O(n) 🔥 Takeaway: Using a reverse transformation + hashmap lookup converts a nested loop problem into a linear scan — a classic optimization pattern! #Day565 #750DaysOfCode #LeetCode #Java #DataStructures #Algorithms #CodingJourney #HashMap #ProblemSolving
To view or add a comment, sign in
-
-
🚀 #Day54 of #100DaysDSAChallenge Solved #LeetCode160: Intersection of Two Linked Lists The problem asks us to find the node where two singly linked lists intersect. 🔹 Approach: 🔸 Brute Force Store nodes of one list in a hashmap/set and check while traversing the second list. ⏱️ Time: O(n + m) | 📦 Space: O(n) 🔸 Better Find lengths of both lists, move the longer list ahead by the difference, then traverse together to find intersection. ⏱️ Time: O(n + m) | 📦 Space: O(1) 🔸 Optimal Use two pointers and switch heads when reaching null so both traverse equal distance and meet at intersection. ⏱️ Time: O(n + m) | 📦 Space: O(1) 💡 Great example of improving from extra space → alignment → elegant pointer trick. 🔗 Github repo: https://lnkd.in/g_rSFCh8 #100DaysOfDSA #DSA #LeetCode #Java #Algorithms #DataStructures #KunalKushwaha #Striver #GeeksForGeeks #ProblemSolving #CodingJourney #LearningInPublic #InterviewPrep #PlacementPreparation 🚀
To view or add a comment, sign in
-
-
Day 16 of my #30DayCodeChallenge: Navigating the Twist! The Problem: Search in Rotated Sorted Array. The Logic: While a standard Binary Search assumes a fully linear sequence, a rotated array introduces a "break point." The key is realizing that at any given mid-point, at least one half of the array must be sorted. 1. Identify the Sorted Half: In every iteration, I compare nums [left] with nums [mid]. If nums [left] <= nums [mid], the left side is sorted. Otherwise, the right side is sorted. 2. Range Check: Instead of searching blindly, I check if the target actually lies within the bounds of that sorted half. 3. The Result: By consistently discarding half of the search space based on these sorted properties, we pinpoint the target index or return -1 if it doesn't exist. Cracking the code, one rotation at a time. Onward to Day 17! #Java #Algorithms #DataStructures #BinarySearch #ProblemSolving #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 71/100 Completed ✅ 🚀 Solved LeetCode – Reshape the Matrix (Java) ⚡ Implemented an efficient matrix transformation approach by mapping elements from the original matrix to the reshaped matrix using a single traversal. Instead of creating intermediate structures, used index manipulation (count / c, count % c) to place elements correctly while maintaining row-wise order. 🧠 Key Learnings: • Understanding how to map 2D indices into a linear traversal • Efficiently converting between different matrix dimensions • Handling edge cases where reshape is not possible • Writing clean and optimized nested loop logic 💯 This problem strengthened my understanding of matrix traversal and index mapping techniques, which are very useful in array and grid-based problems. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Day 95 of #365DaysOfLeetCode Challenge Today’s problem: **Path Sum III (LeetCode 437)** This one looks like a typical tree problem… but the optimal solution introduces a powerful concept: **Prefix Sum + HashMap in Trees** 💡 **Core Idea:** Instead of checking every possible path (which would be slow), we track **running sums** as we traverse the tree. 👉 If at any point: `currentSum - targetSum` exists in our map → we’ve found a valid path! 📌 **Approach:** * Use DFS to traverse the tree * Maintain a running `currSum` * Store prefix sums in a HashMap * Check how many times `(currSum - targetSum)` has appeared * Backtrack to maintain correct state ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Prefix Sum isn’t just for arrays — it can be **beautifully extended to trees**. This problem completely changed how I look at tree path problems: 👉 From brute-force traversal → to optimized prefix tracking 💭 **Key takeaway:** When a problem involves “subarray/paths with a given sum,” think: ➡️ Prefix Sum + HashMap #LeetCode #DSA #BinaryTree #PrefixSum #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
Day 23 of my #30DayCodeChallenge: The Art of Pruning! The Problem: Permutations II. Generating all unique permutations of a collection that contains duplicates. The challenge isn't just finding the arrangements, but ensuring we don't repeat work or results. The Logic: This problem is a deep dive into Backtracking with a strategic Pruning layer: 1. The Frequency/State Tracking: Since we have duplicate numbers, we can't just rely on the values themselves. I used a vis [] (visited) boolean array to keep track of which specific index in the array is currently being used in our recursion tree. 2. Sorting for Symmetry Breaking: Before starting the recursion, sorting the array is the secret sauce. By grouping identical numbers together, we can easily identify when we are about to make a "dur"-ate choice." 3. Backtracking: Standard push, recurse, and pop. We explore every valid path, then "undo" our choice by setting vis [j] = false to backtrack and try the next possibility. One step closer to mastery. The logic is getting sharper! Onward to Day 24! #Java #Algorithms #DataStructures #Backtracking #LeetCode #150DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 64 of #100DaysOfCode Solved 222. Count Complete Tree Nodes on LeetCode 🔗 🧠 Key Insight: In a complete binary tree, all levels are fully filled except possibly the last, and nodes are as left as possible. 👉 This property helps us optimize beyond simple traversal ⚙️ Approach (Simple DFS - Your Solution): 1️⃣ If root is null → return 0 2️⃣ Recursively count: 🔹 left = countNodes(root.left) 🔹 right = countNodes(root.right) 3️⃣ Total nodes: 👉 1 + left + right ⏱️ Time Complexity: Current → O(n) Optimized → O(log² n) 📦 Space Complexity: O(h) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DivideAndConquer #Java #InterviewPrep #CodingJourney
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