Day 35 of #75DaysOfLeetCode 🚀 LeetCode 1448 — Count Good Nodes in Binary Tree Just solved an interesting tree problem that really strengthens DFS concepts! 🌳 👉 Problem Insight: A node in a binary tree is considered “good” if no node on the path from root to it has a value greater than it. 💡 Approach: Traverse the tree using DFS Keep track of the maximum value seen so far If current node ≥ max_so_far → it's a good node Update max and continue traversal 🧠 This problem is a great example of: ✔️ Tree traversal (DFS) ✔️ Passing state in recursion ✔️ Decision making at each node ⏱ Complexity: Time: O(n) Space: O(h) 💻 Java Code: class Solution { public int goodNodes(TreeNode root) { return dfs(root, root.val); } private int dfs(TreeNode node, int maxSoFar) { if (node == null) return 0; int count = 0; if (node.val >= maxSoFar) { count = 1; maxSoFar = node.val; } count += dfs(node.left, maxSoFar); count += dfs(node.right, maxSoFar); return count; } } 🔥 Key Takeaway: Always think about what information needs to be carried along the recursion path — here, it's the maximum value so far. #LeetCode #DataStructures #BinaryTree #DFS #Java #CodingInterview #100DaysOfCode
LeetCode 1448: Count Good Nodes in Binary Tree
More Relevant Posts
-
Day 63 — LeetCode Progress (Java) Problem: Crawler Log Folder Required: Given a list of folder operations, return the minimum number of operations needed to go back to the main folder. Idea: Track the current depth like a counter — move forward increases depth, move back decreases depth, and staying does nothing. Approach: Initialize a variable to track current depth. Traverse each log: "../" → move up (decrease depth, but not below 0) "./" → stay in the same folder "x/" → move into a subfolder (increase depth) Final depth represents the number of steps needed to return to the main folder. Time Complexity: O(n) Space Complexity: O(1) #LeetCode #DSA #Java #Simulation #Strings #Algorithms #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 7: Cracking the "Two Pointer" Pattern 🚀 Today, I dived into LeetCode 167 (Two Sum II) to master the Two Pointer technique! While the standard Two Sum problem is often solved with a Hash Map, a Sorted Array gives us a secret advantage. By using two pointers—one at the start and one at the end—we can find the target sum in $O(n)$ time and $O(1)$ space. No extra memory needed! 🧠 💡 Key Takeaway: The magic happens in the movement: Sum < Target? Move the left pointer to grab a larger value. Sum > Target? Move the right pointer to grab a smaller value. Pro Tip: Always watch out for 1-indexed requirements! Adding that +1 to your return indices is the difference between a "Wrong Answer" and "Accepted." ✅ 🛠️ The Logic (Java): Java while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } One week down, more patterns to go! Following the roadmap from the "25 DSA Patterns" series. 📈 #DSA #LeetCode #CodingChallenge #Java #TwoPointers #SoftwareEngineering #Consistency
To view or add a comment, sign in
-
-
🚀 Day 62 of #100DaysOfCode 🌱 Topic: Trees / Recursion ✅ Problem Solved: LeetCode 112 – Path Sum 🛠 Approach: Used DFS (recursion) to explore all root-to-leaf paths. Base Case: If node is null → return false If leaf node: Check if target == node.val → return result Otherwise: Reduce target → target - node.val Recurse on left and right subtree #100DaysOfCode #Day62 #DSA #Trees #Recursion #DFS #LeetCode #Java #BinaryTree #ProblemSolving #CodingJourney #Consistency
To view or add a comment, sign in
-
-
Day 68/100 Completed ✅ 🚀 Solved LeetCode – Split Array Largest Sum (Java) ⚡ Applied an efficient Binary Search on Answer approach to split the array into k subarrays such that the largest subarray sum is minimized. Instead of trying all possible splits, optimized the solution by searching within the range of maximum element and total sum, and validating using a greedy strategy. 🧠 Key Learnings: Identifying binary search applicability in partition-based problems Defining search space using max element (lower bound) and total sum (upper bound) Using greedy logic to check feasibility of splitting into k subarrays Minimizing the maximum subarray sum through efficient validation 💯 This problem strengthened my understanding of partition problems and reinforced how binary search can be used for optimization rather than direct searching. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #binarysearch #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 74 of #100DaysOfLeetCode 💻✅ Solved #162. Find Peak Element problem in Java. Approach: • Used Binary Search technique to efficiently find the peak element • Set two pointers, left at start and right at end of the array • Calculated mid index using safe mid formula • Compared nums[mid] with nums[mid + 1] to determine direction • If mid element is smaller, moved search space to right half • Otherwise, moved search space to left half including mid • Continued until left and right pointers converged • Final position (left == right) represents the peak index Performance: ✓ Runtime: 0 ms (Beats 100.00% submissions) 🚀 ✓ Memory: 44.32 MB (Beats 25.49% submissions) Key Learning: ✓ Strengthened understanding of Binary Search on unsorted arrays ✓ Learned how to apply divide-and-conquer beyond traditional searching ✓ Improved intuition for peak finding using neighbor comparison ✓ Practiced optimizing search space instead of linear scanning Learning one problem every single day 🚀 #Java #LeetCode #DSA #BinarySearch #Arrays #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Day 26/75: Logic over Luck When you see a problem that asks for $O(\log n)$ time, your mind should immediately jump to Binary Search. But what if the data isn't perfectly sorted? Today’s LeetCode problem—Search in Rotated Sorted Array—is all about conditions. My approach in Java: Calculate mid safely. Determine if the left half is sorted (nums[left] <= nums[mid]). If yes, check if the target is in that range; otherwise, search the right. If no, it means the right half must be sorted. Result? 0ms Runtime and another problem checked off the list. ✅ Day 26 complete. Every problem is a lesson in thinking more clearly. See you for Day 27! 💻🔥 #Consistency #CodingJourney #LeetCodeChallenge #JavaDeveloper #TechGrowth #100DaysOfCode
To view or add a comment, sign in
-
-
Day 76/100 Completed ✅ 🚀 Solved LeetCode – Search a 2D Matrix (Java) ⚡ Implemented an optimized binary search approach by treating the 2D matrix as a flattened sorted array. Converted 1D index into 2D coordinates (row = mid / m, col = mid % m) to efficiently locate the target in O(log(m × n)) time. 🧠 Key Learnings: • Applying binary search on a 2D matrix • Converting 1D index to 2D (row & column mapping) • Reducing time complexity from O(m × n) → O(log(m × n)) • Importance of problem observation (matrix behaves like sorted array) 💯 This problem strengthened my understanding of binary search variations and how to apply it beyond simple 1D arrays. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #binarysearch #arrays #optimization #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🔥 𝗗𝗮𝘆 𝟵𝟰/𝟭𝟬𝟬 — 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝟭𝟱𝟯𝟵. 𝗞𝘁𝗵 𝗠𝗶𝘀𝘀𝗶𝗻𝗴 𝗣𝗼𝘀𝗶𝘁𝗶𝘃𝗲 𝗡𝘂𝗺𝗯𝗲𝗿 | 🟢 Easy | Java Marked as Easy — but the optimal solution is pure binary search brilliance. 🎯 🔍 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 Given a sorted array, find the kth missing positive integer. Linear scan works — but can we do O(log n)? 💡 𝗧𝗵𝗲 𝗞𝗲𝘆 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 At index i, the value arr[i] should be i+1 in a complete sequence. So missing numbers before arr[i] = arr[i] - 1 - i This lets us binary search on the count of missing numbers! ⚡ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 — 𝗕𝗶𝗻𝗮𝗿𝘆 𝗦𝗲𝗮𝗿𝗰𝗵 ✅ If arr[mid] - 1 - mid < k → not enough missing numbers yet, go right ✅ Else → too many missing, go left ✅ After the loop, left + k gives the exact answer 𝗪𝗵𝘆 𝗹𝗲𝗳𝘁 + 𝗸? After binary search, left is the index where the kth missing number falls beyond. left numbers exist in the array before that point, so the answer is left + k. No extra passes needed. ✨ 📊 𝗖𝗼𝗺𝗽𝗹𝗲𝘅𝗶𝘁𝘆 ⏱ Time: O(log n) — vs O(n) linear scan 📦 Space: O(1) This is a perfect example of binary searching on a derived condition, not just a value. A real upgrade from the naive approach. 🧠 📂 𝗙𝘂𝗹𝗹 𝘀𝗼𝗹𝘂𝘁𝗶𝗼𝗻 𝗼𝗻 𝗚𝗶𝘁𝗛𝘂𝗯: https://lnkd.in/gVYcjNS6 𝟲 𝗺𝗼𝗿𝗲 𝗱𝗮𝘆𝘀. 𝗧𝗵𝗲 𝗳𝗶𝗻𝗶𝘀𝗵 𝗹𝗶𝗻𝗲 𝗶𝘀 𝗿𝗶𝗴𝗵𝘁 𝘁𝗵𝗲𝗿𝗲! 🏁 #LeetCode #Day94of100 #100DaysOfCode #Java #DSA #BinarySearch #Arrays #CodingChallenge #Programming
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