🚀 Mastering Java Through LeetCode 🧠 Day 32 Today I solved an Easy-level Tree problem that strengthened my understanding of Recursion + Depth Calculation — a fundamental concept for tree-based problems 📌 LeetCode Problem Solved: Q.104. Maximum Depth of Binary Tree 💭 Problem Summary: Given a binary tree, the task is to find the maximum depth — i.e., the number of nodes along the longest path from root to leaf. 🧠 Approach (Optimal): Instead of iterating level by level, I used a clean recursive approach: ✔️ If node is null → return 0 ✔️ Recursively calculate left subtree depth ✔️ Recursively calculate right subtree depth ✔️ Return 1 + max(left, right) ⚡ Key Learning: Recursion makes tree problems much simpler when you think in terms of “what should each function return for a node?” Complexity: Time: O(n) Space: O(h) Takeaway: Tree problems become easier once you master recursion and start recognizing patterns. Consistency is the key — showing up every day #Day32 #LeetCode #Java #DSA #CodingJourney #Recursion #BinaryTree #100DaysOfCode #SoftwareEngineering
Max Depth of Binary Tree Java Solution
More Relevant Posts
-
🚀 Mastering Java Through LeetCode 🧠 Day 33 Not all nodes are “Good”… but finding them made me better at Trees 📌 LeetCode Problem Solved: Q.1448 – Count Good Nodes in Binary Tree 💭 Problem Summary: A node is called “Good” if no node on the path from root to it has a greater value. 🎯 Approach: ✔ Used DFS (Depth First Search) ✔ Tracked the maximum value seen so far in the path ✔ If current node ≥ maxSoFar → count it as a Good Node ✔ Updated max and continued recursion 🧠 Key Insight: Instead of storing the full path, just carry maxSoFar — simple yet powerful optimization! 💡 Complexity: ⏱ Time: O(N) 📦 Space: O(H) 🔥 What I Learned: How to maintain state during recursion Clean way to solve tree problems using DFS Thinking in terms of path-based conditions Consistency builds confidence 💪 Day 33 done… Let’s keep going 🚀 #Java #LeetCode #DataStructures #Algorithms #CodingJourney #100DaysOfCode #DSA #Tech #Learning
To view or add a comment, sign in
-
-
Day 73 of #90DaysDSAChallenge Solved LeetCode 451: Sort Characters By Frequency Learned an important Java design concept today. Problem Overview: The task was to sort characters in a string based on descending frequency. What confused me initially: Why create a separate Freq class instead of just using HashMap and PriorityQueue directly? Key Learning: PriorityQueue stores one complete object at a time. For this problem, each item needs two pieces of data together: Character Frequency Example: Instead of storing: e and 2 separately We package them as: Freq('e', 2) That custom class acts like a container holding both values in one object, so PriorityQueue can compare and sort them correctly. Why this matters: This taught me that custom classes in Java are often not about complexity, they simply bundle related data into one manageable unit. Alternative approach: We can also use Map.Entry<Character, Integer> instead of creating a custom class, but building Freq makes the logic easier to understand while learning. Today’s takeaway: Not every class is for business logic — sometimes it exists just to package data cleanly. #Java #90DaysDSAChallenge #LeetCode #PriorityQueue #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Solved LeetCode 17 – Letter Combinations of a Phone Number using backtracking in Java. Approach: Mapped each digit (2–9) to its corresponding characters using a simple array for O(1) access. Then used backtracking to build combinations digit by digit. For every digit: Pick each possible character Append → explore next digit → backtrack Key idea: Treat it like a tree of choices, where each level represents a digit and branches represent possible letters. Key learnings: Backtracking = build → explore → undo StringBuilder helps avoid unnecessary string creation Problems like this are about systematic exploration of choices Time Complexity: O(4^n * n) Space Complexity: O(n) recursion stack + output Consistent DSA practice is strengthening pattern recognition day by day. #Java #DSA #Backtracking #LeetCode #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 97 - LeetCode Journey Solved LeetCode 496: Next Greater Element I in Java ✅ This is a perfect example of combining Monotonic Stack + HashMap for efficiency. Instead of checking each element one by one, I precomputed the next greater elements using a stack and stored them in a map for quick lookup. Smart preprocessing saves time 💡 Key idea: Traverse nums2, use a stack to find next greater elements, and map them for instant access. Key takeaways: • Monotonic Stack pattern • Using HashMap for fast queries • Avoiding nested loops (O(n²) → O(n)) • Preprocessing for optimization ✅ All test cases passed ⚡ O(n) time and O(n) space Stack + Map combo is a game changer for these types of problems 🔥 #LeetCode #DSA #Java #Stack #MonotonicStack #HashMap #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Day 93 - LeetCode Journey Solved LeetCode 9: Palindrome Number in Java ✅ At first glance, it feels like a string problem… but the real challenge is solving it without converting to string. Instead of reversing the whole number, I reversed only half of it and compared both parts. This avoids overflow and keeps it efficient. Smart approach > brute force 💡 Key takeaways: • Handling edge cases (negative numbers, trailing zeroes) • Reversing only half of the number • Avoiding extra space (no string conversion) • Writing optimized mathematical logic ✅ All test cases passed ⚡ O(log n) time and O(1) space Sometimes the best solutions are the simplest ones, just a different way of thinking 🔥 #LeetCode #DSA #Java #Math #ProblemSolving #CodingJourney #InterviewPrep #Consistency #100DaysOfCode
To view or add a comment, sign in
-
-
Day 11 of Learning Java Streams Today I worked on a simple but insightful problem: Extract all digits from a string and calculate their sum. I first approached it in a more step-by-step (brute force style) using streams: Converted characters to objects Filtered digits Converted each digit to String Then to Integer Finally used reduce() to compute the sum While it worked, I realized it involved unnecessary conversions and overhead. Then I explored a more optimized approach: Stayed within IntStream Filtered digits directly Used Character.getNumericValue() Leveraged built-in sum() This made the solution cleaner, faster, and more efficient. Key Learning: Choosing the right stream type (IntStream vs Stream<T>) can significantly simplify logic and improve performance. Small improvements like avoiding unnecessary transformations can make code more readable and efficient. #Java #JavaStreams #CodingJourney #LearningInPublic #BackendDevelopment #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
Day 10/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Polymorphism Polymorphism means “many forms” — the same method behaves differently depending on the object. 💻 Practice Code: 🔸 Example Program class Animal { void sound() { System.out.println("Animal makes sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); // Upcasting a.sound(); // Runtime polymorphism } } 📌 Key Learnings: ✔️ Same method → different behavior ✔️ Achieved using method overriding ✔️ Based on object type (runtime) 🎯 Focus: Understanding dynamic behavior using inheritance and method overriding 🔥 Interview Insight: Polymorphism is a core OOP concept and widely used in real-world applications. #Java #100DaysOfCode #Polymorphism #OOP #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
🚀 Mastering Java Through LeetCode 🧠 Day 17 of My DSA Journey Today I solved another problem from the LeetCode list to improve my understanding of arrays and prefix sum concepts. 📌 LeetCode Problem Solved Today: Q.1732. Find the Highest Altitude In this problem, a biker starts a road trip from altitude 0, and we are given an array that represents the gain or loss in altitude between points. The task is to find the highest altitude reached during the trip. Method 1: Using ArrayList (My 1st Approach) I stored all altitudes step by step in an ArrayList and then used Collections.max() to find the highest altitude. Method 2: Optimized Approach (My Second Approach Without Extra Space) Instead of storing all values, we can directly track the maximum altitude while iterating. 💻 Optimized Java Solution class Solution { public int largestAltitude(int[] gain) { int altitude = 0; int maxAltitude = 0; for (int g : gain) { altitude += g; maxAltitude = Math.max(maxAltitude, altitude); } return maxAltitude; } } Example: Input: gain = [-5,1,5,0,-7] Altitudes formed: [0, -5, -4, 1, 1, -6] Highest altitude = 1 Consistent practice is helping me strengthen my DSA and problem-solving skills step by step. #LeetCode #DSA #Java #CodingJourney #ProblemSolving #ArrayList #100DaysOfCode #SPPU #EngineeringLife #TechCommunity #CDAC
To view or add a comment, sign in
-
-
Day 66 of #100DaysOfLeetCode 💻✅ Solved #3427. Sum of Variable Length Subarrays problem in Java. Approach: • Iterated through each index of the array • Determined the starting index using i - nums[i] • Ensured the start index does not go below 0 • Calculated sum of elements from start to current index i • Added each subarray sum to the total Performance: ✓ Runtime: 1 ms (Beats 99.90% submissions) ✓ Memory: 45.22 MB (Beats 56.30% submissions) Key Learning: ✓ Practiced handling variable-length subarrays ✓ Improved understanding of index-based range calculations ✓ Strengthened nested loop logic for array problems Learning one problem every single day 🚀 #Java #LeetCode #DSA #Arrays #PrefixSum #ProblemSolving #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 DSA Journey — LeetCode Practice 📌 Problem: Maximum Depth of Binary Tree 💻 Language: Java 🔹 Approach: To solve this problem, I used Breadth-First Search (BFS) with a Queue to perform level-order traversal of the binary tree. • Start by adding the root node to the queue • Traverse the tree level by level • For each level, process all nodes currently in the queue • Add left and right children of each node to the queue • Increment the level count after completing each level 📌 Logic Insight: Each iteration of the outer loop represents one level of the tree, which directly helps in calculating the maximum depth. ⏱ Time Complexity: O(n) 🧩 Space Complexity: O(n) (queue storage in worst case) 💡 Key Learning: This problem helped me understand how level-order traversal (BFS) can be used not just for traversal, but also for solving structural problems like finding tree depth efficiently. It also reinforced the importance of queue-based processing in trees. #DSA #Java #LeetCode #BinaryTree #BFS #Queue #CodingJourney #ProblemSolving #LearningInPublic #TreeTraversal
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