Day 37 of #75DaysofLeetCode 🚀 LeetCode 1372 – Longest ZigZag Path in a Binary Tree Just solved an interesting tree problem that really tests your understanding of DFS + state tracking 🌳 🔍 Problem Insight: A ZigZag path alternates between left ↔ right at every step. The goal is to find the longest such path in a binary tree. 💡 Key Idea: At every node, we track: Current direction (left or right) Current path length We have two choices: Continue the ZigZag → increase length Restart from opposite direction → reset length 🧠 Approach (DFS): Use recursion to explore both directions Keep updating a global maximum Try starting from both left and right 📊 Complexity: Time: O(N) Space: O(H) (recursion stack) 🔥 Takeaway: This problem is a great example of how tracking state in recursion can simplify complex tree traversals. #LeetCode #DataStructures #BinaryTree #DSA #CodingInterview #Java #100DaysOfCode
LeetCode 1372: Longest ZigZag Path in Binary Tree
More Relevant Posts
-
💡 Day 54 of LeetCode Problem Solved! 🔧 🌟 560. Subarray Sum Equals K 🌟 🔗 Solution Code: https://lnkd.in/g5VwiFKd 🧠 Approach: Prefix Sum & Hash Map Store cumulative sums in a Map Check for (current_sum - k) to find matching subarrays in one pass ⚡ Key Learning: Mastering the Prefix Sum + HashMap pattern is a game-changer for transforming $O(n^2)$ subarray problems into efficient $O(n)$ solutions. ⏱️ Complexity: Time: O(n) Space: O(n) #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #PrefixSum #DataStructures
To view or add a comment, sign in
-
-
Day 56 : Crushing Binary Trees on LeetCode 💡 Today’s live practical session in Alpha Plus 7.0 We focused on some of the most challenging Binary Tree questions on LeetCode, breaking down the logic behind them. What I practiced today: ✅ Tree Diameter: understand the logic to calculate the absolute longest path between any two nodes in the entire tree. ✅ Maximum Path Sum: Tackled a famous "Hard" level problem! Figured out how to find the path with the highest possible sum, even if it doesn't pass through the root. ✅ Target Deletion: Wrote the recursive code to systematically find and delete leaf nodes that match a specific target value. #BinaryTree #LeetCode #ProblemSolving #DSA #Java #SoftwareEngineering #100DaysOfCode #ApnaCollege
To view or add a comment, sign in
-
-
🚀 Day 571 of #750DaysOfCode 🚀 🔍 Problem Solved: Sum of Distances Today’s problem looked like a classic brute-force trap 👀 At first glance, comparing every pair gives an O(n²) solution — but with constraints up to 10⁵, that’s not going to work. 💡 Key Insight: Instead of comparing all pairs, we can: 👉 Group indices of the same value 👉 Use prefix sums to efficiently calculate distances 🧠 Approach: Group indices by value (using HashMap) For each group: Build prefix sum of indices For each index: Left contribution → i * count - sum Right contribution → sum - i * count Combine both to get final result 📈 Complexity: Time: O(n) Space: O(n) ✨ Takeaway: When you see distance-based problems: 👉 Think in terms of contributions instead of pair comparisons 👉 Prefix sums can turn expensive computations into linear time Another strong pattern added to the toolkit 💪 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #PrefixSum #Algorithms #LearningEveryday
To view or add a comment, sign in
-
-
Day 51/100 – LeetCode Challenge Problem: Third Maximum Number Today I solved the “Third Maximum Number” problem, which focuses on identifying the third distinct maximum value in an array. The key challenge here was handling duplicates while keeping track of the top three distinct values. Instead of sorting the array directly, I used a set to eliminate duplicates first. This simplified the problem by ensuring that only unique values were considered. From there, I handled two cases. If there were fewer than three distinct numbers, I returned the maximum. Otherwise, I iterated through the set and tracked the top three maximum values using variables, updating them as I encountered larger numbers. This approach avoids unnecessary sorting and keeps the logic efficient and controlled. The solution runs in O(n) time with O(n) space complexity due to the set. This problem reinforced the importance of handling duplicates carefully and thinking about edge cases before jumping into implementation. Fifty-one days in. The focus is now on writing cleaner logic with fewer assumptions. #100DaysOfLeetCode #Java #DSA #Arrays #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Today I solved Two Sum (LeetCode #1 - Easy) 💡 🔍 Problem: Find two indices such that their values add up to the target. 🧠 Approach I used: HashMap Instead of checking every pair (O(n²)), I used a HashMap to optimize the solution. 👉 Steps: Calculate complement = target - current element Check if complement exists in the map If yes → return indices ✅ If no → store the element in the map ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(n) 💡 This problem helped me understand how using extra space can reduce time complexity. 📌 Key Learning: “Optimize brute force by using HashMap for faster lookups.” #DSA #Java #LeetCode #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 4 of My LeetCode Journey Solved today’s POTD (Problem of The Day): Closest Equal Element Queries (Medium) 📝 Problem Summary Given a circular array, for each query index, find the minimum distance to another index having the same value. If no such index exists, return -1. 🧠 Intuition Instead of checking every index for each query (brute force), I realized we only need to focus on positions where the same value occurs. 💡 Approach ✔️ Used a HashMap to store: value → list of indices ✔️ For each query: Found the index position using binary search Checked only left and right neighbors (closest possible matches) ✔️ Calculated distance using circular logic: min(|i - j|, n - |i - j|) 📚 Key Learning Smart preprocessing can reduce time complexity significantly In circular arrays, always consider wrap-around distance Nearest element problems often reduce to adjacent comparisons #LeetCode #Day4 #DSA #ProblemOfTheDay #Java #CodingJourney #PlacementPreparation
To view or add a comment, sign in
-
-
🚀 Day 38 of my #100DaysOfCode Journey Today, I solved the LeetCode problem: Maximum Product of Two Elements in an Array. Problem Insight: Given an integer array, the goal is to find two elements such that: (nums[i] - 1) * (nums[j] - 1) is maximized Approach: • First, sort the array using Arrays.sort() • Use two nested loops to check all possible pairs • For each pair, calculate → (nums[i] - 1) * (nums[j] - 1) • Keep track of the maximum product Time Complexity: • O(n²) — due to nested loops Space Complexity: • O(1) — no extra space used Key Learnings: • Understanding operator precedence is very important in expressions • Sorting helps in simplifying many problems • Even simple problems can have optimized solutions beyond brute force Takeaway: Brute force helps in understanding the problem deeply, but optimization (like using the two largest elements directly) makes the solution efficient 🚀 #DSA #Java #LeetCode #100DaysOfCode #CodingJourney #ProblemSolving #Arrays
To view or add a comment, sign in
-
-
Day 42/100 – LeetCode Challenge Problem: Top K Frequent Elements Today I worked on the “Top K Frequent Elements” problem, which focuses on identifying the k most frequent elements from an array. I approached this by first using a HashMap to store the frequency of each element. Once the frequencies were calculated, I converted the map into a list of pairs and sorted it based on frequency. From the sorted structure, I extracted the top k elements by selecting from the highest frequency values. This approach keeps the logic straightforward and easy to follow, especially when prioritizing clarity before optimization. While sorting introduces additional overhead, it provides a clean way to rank elements based on frequency. The solution runs in O(n log n) time due to sorting, with O(n) space complexity. This problem reinforced the importance of frequency counting combined with sorting techniques, and how different approaches can be chosen depending on the trade-off between simplicity and efficiency. Forty-two days in. Consistency is now translating into structured thinking. #100DaysOfLeetCode #Java #DSA #Hashing #Sorting #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
💡 Day 55 of LeetCode Problem Solved! 🔧 🌟21. Merge Two Sorted Lists🌟 🔗 Solution Code: https://lnkd.in/gU7m-4wH 🧠 Approach: • Recursive Merge • Checked for null node base cases to identify the ends of the lists. • Recursively compared the current node values of list1 and list2. • Attached the smaller node to point to the recursively merged result of the remaining nodes. ⚡ Key Learning: • Leveraging recursion drastically simplifies Linked List operations, turning complex pointer-splicing logic into an elegant and readable sequence! ⏱️ Complexity: Time: • O(n + m) — where n and m are the lengths of the two lists Space. • O(n + m) — due to the recursion stack #LeetCode #Java #DSA #ProblemSolving #Consistency #100DaysOfCode #CodingJourney #LinkedList #Recursion
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟕𝟕 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding all elements that appear more than n/3 times in an array. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Majority Element II 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 – 𝐇𝐚𝐬𝐡𝐌𝐚𝐩 • Counted frequency of each element using a map • Calculated threshold = n / 3 • Collected elements whose frequency exceeded the threshold 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • At most 2 elements can appear more than n/3 times • HashMap is straightforward for frequency counting • Understanding constraints helps reduce possibilities • This problem has an optimized Boyer-Moore Voting (extended) solution 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(n) • Space: O(n) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Constraints often reveal hidden patterns — understanding them leads to better optimizations. 77 days consistent 🚀 On to Day 78. 🔗 Problem Link: https://lnkd.in/dDwdWYJs #DSA #Arrays #HashMap #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
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