🚀 Daily DSA Practice – Day 37 | Tree Depth, Height & Diameter (Java) As part of my ongoing Data Structures & Algorithms preparation, today I focused on tree depth and height–based problems, which rely heavily on DFS recursion and postorder traversal to compute values from bottom to top. 📌 Problems Solved (LeetCode): • 104. Maximum Depth of Binary Tree – Calculated tree height using recursive DFS • 111. Minimum Depth of Binary Tree – Handled edge cases where one child is null • 543. Diameter of Binary Tree – Used postorder traversal to compute the longest path between any two nodes 🎯 Key Learnings: ✔ Difference between depth and height in binary trees ✔ Why postorder traversal is ideal for bottom-up calculations ✔ Managing global/state variables in recursive solutions ✔ Writing clean and efficient DFS-based tree algorithms These problems are frequently asked in coding interviews because they test recursion mastery, edge-case handling, and tree traversal intuition, which are essential for backend and system-level problem solving. #DSA #LeetCode #Java #BinaryTree #DFS #Recursion #TreeHeight #ProblemSolving #InterviewPreparation #BackendDeveloper #SoftwareEngineer
Java Binary Tree Depth Height Diameter LeetCode Solutions
More Relevant Posts
-
🚀 Daily DSA Practice – Day 39 | Binary Tree Properties & Validation (Java) Continuing my Data Structures & Algorithms preparation, today I focused on binary tree property-checking problems — validating structure, balance, and symmetry using DFS recursion and subtree comparisons. 📌 Problems Solved (LeetCode): • 100. Same Tree – Compared two trees node-by-node using recursion • 101. Symmetric Tree – Checked mirror structure using recursive subtree comparison • 110. Balanced Binary Tree – Determined height balance using bottom-up DFS 🎯 Key Learnings: ✔ Writing clean recursive functions for subtree comparison ✔ Understanding mirror logic in symmetric trees ✔ Optimizing balance checks using postorder traversal ✔ Handling edge cases like null nodes and height differences These problems are frequently asked in technical interviews because they test recursion clarity, structural reasoning, and edge-case handling, which are critical for backend and system-level coding. #DSA #LeetCode #Java #BinaryTree #Recursion #TreeValidation #ProblemSolving #InterviewPreparation #BackendDeveloper #SoftwareEngineer
To view or add a comment, sign in
-
🚀 Daily DSA Practice – Day 40 | Path Sum & Backtracking in Binary Trees (Java) Continuing my Data Structures & Algorithms journey, today I focused on path-based tree problems, combining DFS recursion and backtracking to explore root-to-leaf and multi-path scenarios — a key pattern in coding interviews. 📌 Problems Solved (LeetCode): • 112. Path Sum – Checked existence of a root-to-leaf path matching a target sum • 113. Path Sum II – Stored all valid root-to-leaf paths using backtracking • 437. Path Sum III – Counted total paths using prefix-sum optimization with DFS 🎯 Key Learnings: ✔ Difference between existence check vs storing paths vs counting paths ✔ Practical use of backtracking to manage dynamic path lists ✔ Prefix-sum technique for optimizing multi-path calculations ✔ Improved understanding of recursion state management and edge cases These problems highlight how tree + backtracking patterns are widely used in search algorithms, hierarchical data analysis, and optimization tasks, making them highly relevant for product-based company interviews. #DSA #LeetCode #Java #BinaryTree #Backtracking #DFS #PathSum #ProblemSolving #InterviewPreparation #BackendDeveloper #SoftwareEngineer
To view or add a comment, sign in
-
🚀 DSA Series – Problem Solving Today I solved a classic String problem: Removing Duplicate Characters. 🧩 Problem Statement Given a string, remove duplicate characters while maintaining the order of first occurrence. Example: Input: `"programming"` Output: `"progamin"` 🧠 Optimized Approach (Using Boolean Array) Instead of using a HashSet, I used a boolean array to track characters. This works great when the character set is limited (like ASCII). 🔹 Step-by-step Logic 1️⃣ Create a boolean array of size 256 (for all ASCII characters). * Each index represents a character. * Default value is `false` → means character not seen yet. 2️⃣ Create a StringBuilder to store the result. 3️⃣ Traverse the string character by character: * For each character `ch`, check `if (seen[ch] == false)` → Mark it as seen: `seen[ch] = true` → Append it to StringBuilder * If already `true`, skip it (duplicate). 4️⃣ Convert StringBuilder to string — final answer ready ✅ ⏱ Time & Space Complexity Time Complexity: O(n) We traverse the string only once. Space Complexity:O(1) Because the boolean array size is fixed (256), not dependent on input size. 💡 Key Learning Choosing the right data structure matters a lot. Boolean arrays can be faster and more memory-efficient than HashSet when the character range is small. Small optimizations = Big performance impact 🚀 #DSA #Java #ProblemSolving #CodingJourney #Placements #LearningInPublic
To view or add a comment, sign in
-
-
🔥 Day 304 – Daily DSA Challenge! 🔥 Problem: 🎯 Combination Sum II Given an array of candidate numbers (with possible duplicates) and a target value, return all unique combinations where the chosen numbers sum to the target. 👉 Each number can be used at most once in a combination. 💡 Key Insights: 🔹 This is a classic backtracking + pruning problem. 🔹 Sorting the array is crucial to handle duplicates efficiently. 🔹 Skip repeated elements at the same recursion level to avoid duplicate combinations. 🔹 Once a number exceeds the remaining target, we can stop early (thanks to sorting). 🔹 Always move to i + 1 since each element can be used only once. ⚡ Optimized Plan: ✅ Sort the candidates array ✅ Use backtracking to explore all valid combinations ✅ Maintain a temporary list (cur) for the current path ✅ Add the path to result when target == 0 ✅ Skip duplicates using if (i > idx && a[i] == a[i - 1]) ✅ Backtrack after each recursive call ✅ Time Complexity: O(2ⁿ) in the worst case ✅ Space Complexity: O(n) (recursion stack + current combination) 💬 Challenge for you: 1️⃣ What happens if we remove sorting — how do duplicates affect the output? 2️⃣ How is this problem different from Combination Sum I? 3️⃣ Can you convert this recursive solution into an iterative one? #DSA #LeetCode #Backtracking #Recursion #ProblemSolving #Java #KeepCoding
To view or add a comment, sign in
-
-
Contains Duplicate — LeetCode 217 Hi all 👋 Today this is my first post related to a DSA problem. Goal Check whether an array contains duplicate numbers or not. n = Length of array idx = Index of array element Brute Force Approach Select each element and compare it with all other elements in the array. If any same value is found, return "true"; otherwise return "false". Time Complexity: O(n²) Space Complexity: O(1) Reason: every element is compared with others. Better Approach (Sorting) If we sort the array, duplicate elements come next to each other. After sorting, we simply compare adjacent elements. 🕸 Trap Empty array or single element array (idx < n-1) Time Complexity: O(n log n) Space Complexity: Depends on the sorting algorithm. Optimized Approach (Using Set) Before moving forward, let’s recall one important data structure — Set. A set: - Performs operations in average O(1) time - Does not allow duplicates Approach: - Traverse the array from the first element. - Check if the element already exists in the set. - If yes → duplicate found → return "true". - Otherwise, add the element to the set. The key idea: if we encounter the same element again, it means a duplicate exists. Time Complexity: O(n) Space Complexity: O(n) (in worst case when no duplicates exist) 🔁 Trade-off In real-world problems, we often optimize for time complexity. - If extra space is allowed → use Set (best time). - If space is restricted → prefer Sorting. Whenever you see duplicate or frequency type problems, think about: ➡️ Sorting ➡️ HashSet / HashMap If I missed anything or if you have a better approach, please feel free to add it in the comments. Thanks for reading 🙌 #DSA #LeetCode #Java #CodingJourney #DataStructures #Algorithms #ProblemSolving #SoftwareEngineer #TechLearning #InterviewPreparation
To view or add a comment, sign in
-
Day - 88 Maximum Depth of Binary Tree The problem - Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Brute Force - Use level-order traversal (BFS) to visit all nodes level by level, counting the number of levels. This gives O(n) time and O(w) space where w = maximum width, which works but is more complex than needed. Approach Used - •) If root == null, return 0 (empty tree has depth 0). •) Calculate left subtree depth: left = maxDepth(root.left). •) Calculate right subtree depth: right = maxDepth(root.right). •) Return 1 + Math.max(left, right), 1 accounts for current node and Math.max(left, right) selects the deeper subtree. Complexity - Time - O(n), where n = number of nodes. Space - O(h), where h = height of tree. Note - The maximum depth of a binary tree is determined recursively: it's 1 (for the current node) plus the maximum depth of its left and right subtrees. The base case returns 0 for null nodes. This elegant recursive solution naturally follows the tree structure and computes depth in a single pass. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟏𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on grouping logic using arrays + hashing concepts 🗂️ and understanding different ways to build unique keys. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • 🔤 Group Anagrams 🔹 𝐆𝐫𝐨𝐮𝐩 𝐀𝐧𝐚𝐠𝐫𝐚𝐦𝐬 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟏 – 𝐒𝐨𝐫𝐭𝐢𝐧𝐠 𝐁𝐚𝐬𝐞𝐝 • 🔄 Converted each word into a char array • 📊 Sorted the characters • 🔑 Used the sorted string as a key in HashMap • 📦 Grouped words sharing the same sorted key 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 𝟐 – 𝐅𝐫𝐞𝐪𝐮𝐞𝐧𝐜𝐲 𝐀𝐫𝐫𝐚𝐲 𝐁𝐚𝐬𝐞𝐝 • 🔢 Created a frequency array of size 26 • 🧮 Built a unique key using character counts • ⚡ Used computeIfAbsent for cleaner insertion • 📌 Avoided sorting for better efficiency 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • 🧠 Anagrams share identical character distributions • 🔑 The way you build the key defines performance • ⚡ Frequency-array approach avoids O(k log k) sorting • 📊 Combining arrays with hashing improves efficiency 🧠 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Even in array problems, sometimes the real power lies in how you represent the data 🔑 15 days consistent 🔥 On to Day 16 🚀 #DSA #Arrays #Strings #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
⚡ 𝗗𝗮𝘆 𝟳𝟱 𝗼𝗳 𝗠𝘆 𝟭𝟬𝟬 𝗗𝗮𝘆𝘀 𝗼𝗳 𝗗𝗦𝗔 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲! 𝘛𝘰𝘥𝘢𝘺’𝘴 𝘱𝘳𝘰𝘣𝘭𝘦𝘮 𝘸𝘢𝘴 𝘢 𝘨𝘳𝘦𝘢𝘵 𝘮𝘪𝘹 𝘰𝘧 𝙨𝙩𝙧𝙞𝙣𝙜 𝙥𝙧𝙤𝙘𝙚𝙨𝙨𝙞𝙣𝙜 𝙖𝙣𝙙 𝙢𝙖𝙩𝙝𝙚𝙢𝙖𝙩𝙞𝙘𝙖𝙡 𝙩𝙝𝙞𝙣𝙠𝙞𝙣𝙜, 𝘪𝘯𝘴𝘱𝘪𝘳𝘦𝘥 𝘣𝘺 𝘢 𝘳𝘦𝘢𝘭-𝘸𝘰𝘳𝘭𝘥 𝘴𝘺𝘴𝘵𝘦𝘮 𝘸𝘦 𝘢𝘭𝘭 𝘳𝘦𝘤𝘰𝘨𝘯𝘪𝘻𝘦 𝘌𝘹𝘤𝘦𝘭 𝘤𝘰𝘭𝘶𝘮𝘯𝘴. 📌 Problem Solved: 1️⃣ 𝗟𝗲𝗲𝘁𝗰𝗼𝗱𝗲 171: Excel Sheet Column Number ✨ Key Learnings: 🔹 This problem is essentially about 𝗯𝗮𝘀𝗲-𝟮𝟲 𝗻𝘂𝗺𝗯𝗲𝗿 𝗰𝗼𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻, where characters act as digits instead of numbers. 🔹 Iterating through the string and updating the result as result = result * 26 + currentCharValue helps build the column number efficiently. 🔹 It reinforced how 𝗰𝗵𝗮𝗿𝗮𝗰𝘁𝗲𝗿-𝘁𝗼-𝗻𝘂𝗺𝗯𝗲𝗿 𝗺𝗮𝗽𝗽𝗶𝗻𝗴 ('A' → 1 to 'Z' → 26) plays a crucial role in many string-based problems. 🧠 Big Takeaway: Problems that look string-heavy often boil down to 𝘀𝗶𝗺𝗽𝗹𝗲 𝗺𝗮𝘁𝗵 + 𝗶𝘁𝗲𝗿𝗮𝘁𝗶𝗼𝗻 once the pattern is clear. Day 75 completed — slowly but surely stacking fundamentals! 💪🔥 #100DaysOfCode #DSA #Java #Strings #ProblemSolving #LogicBuilding #InterviewPreparation #LeetCode #LearningInPublic #Developers
To view or add a comment, sign in
-
-
Day 47/100 – LeetCode Challenge ✅ Problem: #3013 Divide an Array Into Subarrays With Minimum Cost II Difficulty: Hard Language: Java Approach: Order Statistics with Balanced Trees Time Complexity: O(n log n) Space Complexity: O(n) Key Insight: Track greater count efficiently for two arrays during distribution. Need to compare current element with elements in both arrays - count how many are strictly greater. Used two TreeMaps to maintain sorted frequency counts with lazy rebalancing. Solution Brief: Maintained two balanced multisets (TreeMaps) for both arrays with size management. For each element, computed greater counts using total sizes and tail map views. Rebalanced collections when size constraints were violated to maintain optimal query performance. Advanced data structures for dynamic order statistics #LeetCode #Day47 #100DaysOfCode #HardProblem #DataStructures #TreeMap #Java #Algorithm #CodingChallenge #OrderStatistics #BalancedTrees
To view or add a comment, sign in
-
-
🚀 Daily DSA Practice – Day 42 | Advanced Binary Tree Patterns (Java) Continuing my Data Structures & Algorithms journey, today I focused on advanced binary tree problems that combine recursion, divide-and-conquer, and path optimization techniques — commonly asked in product-based company interviews. 📌 Problems Solved (LeetCode): • 236. Lowest Common Ancestor of a Binary Tree – Identified shared ancestors using recursive DFS subtree checks • 124. Binary Tree Maximum Path Sum – Calculated the highest path sum using postorder traversal and global state tracking • 105. Construct Binary Tree from Preorder and Inorder Traversal – Rebuilt tree structure using divide-and-conquer logic with index mapping 🎯 Key Learnings: ✔ Mastered divide & conquer recursion patterns ✔ Understood how global variables help track optimal path values ✔ Improved intuition for tree reconstruction from traversals ✔ Strengthened problem-solving for hard-level recursive scenarios These problems highlight how advanced tree algorithms are critical in hierarchical data processing, compilers, and system-level architecture, making them extremely valuable for backend and product-engineering interviews. #DSA #LeetCode #Java #BinaryTree #Recursion #DivideAndConquer #TreeAlgorithms #ProblemSolving #InterviewPreparation #SoftwareEngineer #BackendDeveloper
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