🚀 Day 65 of #100DaysOfCode Solved 108. Convert Sorted Array to Binary Search Tree on LeetCode 🔗 🧠 Key Insight: To build a height-balanced BST from a sorted array: 👉 Always pick the middle element as root This ensures: Left half → left subtree Right half → right subtree Balanced structure 🔥 ⚙️ Approach (Divide & Conquer): 1️⃣ Choose middle index: 🔹 mid = start + (end - start) / 2 2️⃣ Create root node: 🔹 node = new TreeNode(nums[mid]) 3️⃣ Build left subtree: 🔹 node.left = build(start, mid - 1) 4️⃣ Build right subtree: 🔹 node.right = build(mid + 1, end) 5️⃣ Return root ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(log n) (recursion stack) #100DaysOfCode #LeetCode #DSA #BinaryTree #BST #DivideAndConquer #Recursion #Java #InterviewPrep #CodingJourney
Convert Sorted Array to Balanced BST on LeetCode
More Relevant Posts
-
**Day 109 of #365DaysOfLeetCode Challenge** Today’s problem: **132 Pattern (LeetCode 456)** This problem looks tricky at first because it asks for a hidden subsequence: Find indices `i < j < k` such that: `nums[i] < nums[k] < nums[j]` That forms the **132 pattern** 💡 **Core Idea: Use a Monotonic Stack** Instead of checking all triplets (**O(n³)** ❌), we scan from **right to left**. Why reverse? Because while moving backward: * We try to build possible `3` values using a stack * Track the best possible `2` using a variable called `third` 👉 If we ever find a number smaller than `third`, then: `nums[i] < third < nums[j]` 📌 **Approach:** * Traverse from end to start * Maintain decreasing stack * Pop smaller elements and update `third` * If current number < `third` → return true ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Some array problems become much easier when traversed **backward instead of forward**. 💭 **Key Takeaway:** When the problem asks for hidden order relations: 👉 Think stacks 👉 Think reverse traversal 👉 Think maintaining candidates dynamically This was a great reminder that brute force is rarely the final answer #LeetCode #DSA #MonotonicStack #Arrays #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
**Day 110 of #365DaysOfLeetCode Challenge** Today’s problem: **Add Two Numbers II (LeetCode 445)** A very elegant **Linked List + Stack** problem. We are given two numbers stored in linked lists where the **most significant digit comes first**. Example: `7243 + 564 = 7807` Lists: `[7,2,4,3] + [5,6,4] = [7,8,0,7]` 💡 **Core Challenge:** Normally addition starts from the **last digit**… But linked lists are given from the **front**. So how do we add from right to left **without reversing the lists**? 📌 **Approach:** 1️⃣ Push digits of both linked lists into stacks 2️⃣ Pop from stacks → gives digits from right to left 3️⃣ Add with carry 4️⃣ Insert new node at the front of result list This preserves correct order naturally ⚡ **Time Complexity:** O(n + m) ⚡ **Space Complexity:** O(n + m) **What I learned today:** Stacks are incredibly useful when you need to process data in **reverse order**. 💭 **Key Takeaway:** If you can’t move backward easily: 👉 Use a stack 👉 Simulate reverse traversal 👉 Build result from front Clean solution. Smart idea. Great interview problem #LeetCode #DSA #LinkedList #Stack #CodingChallenge #ProblemSolving #Java #TechJourney #Consistency
To view or add a comment, sign in
-
-
Day 72/100 Completed ✅ 🚀 Solved LeetCode – Matrix Diagonal Sum (Java) ⚡ Implemented an efficient approach to calculate the sum of both primary and secondary diagonals of a square matrix in a single traversal. Avoided double-counting the center element by handling the odd-sized matrix case separately. 🧠 Key Learnings: • Efficient diagonal traversal in a matrix • Handling overlapping elements (center in odd n) • Writing optimal O(n) solutions instead of nested loops • Clean and concise index-based logic 💯 This problem improved my understanding of matrix patterns and how to optimize traversal by reducing unnecessary iterations. 🔗 Profile: https://lnkd.in/gaJmKdrA #leetcode #datastructures #algorithms #java #matrix #arrays #problemSolving #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 Day 85 of #100DaysOfCode Solved 106. Construct Binary Tree from Inorder and Postorder Traversal on LeetCode 🔗 🧠 Key Insight: 👉 Postorder = Left → Right → Root 👉 Last element in postorder = root of tree 👉 Inorder = Left → Root → Right 👉 Use inorder to split into left & right subtrees ⚙️ Approach (HashMap + Recursion): 1️⃣ Take last element of postorder 🔹 This is the root 2️⃣ Find root index in inorder 🔹 Split inorder into: • Left subtree • Right subtree 3️⃣ Build subtrees recursively: 🔹 Important order: 👉 Build right subtree first, then left (because we are consuming postorder from end) 4️⃣ Use a HashMap: 🔹 Store inorder value → index 👉 For O(1) lookup ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DivideAndConquer #HashMap #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 75 of #100DaysOfCode Solved 103. Binary Tree Zigzag Level Order Traversal on LeetCode 🔗 🧠 Key Insight: This is a variation of level order traversal where: 👉 Levels alternate between left → right and right → left ⚙️ Approach (BFS + Direction Toggle): 1️⃣ Use a queue for level order traversal 2️⃣ Maintain a flag (leftToRight or sign) 🔹 true → left → right 🔹 false → right → left 3️⃣ For each level: 🔹 Create a list 🔹 Traverse all nodes in that level 4️⃣ Insert values based on direction: 🔹 If left → right → addLast(val) 🔹 Else → addFirst(val) 5️⃣ Add level list to result 6️⃣ Flip direction: 👉 sign *= -1 or toggle boolean ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(n) #100DaysOfCode #LeetCode #DSA #BinaryTree #BFS #Queue #Java #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 74/100 – LeetCode Challenge 🔍 Problem Solved: Find the Duplicate Number (287) Today’s problem was a great reminder that sometimes the best solutions come from thinking differently 💡 Instead of using extra space or modifying the array, I used Floyd’s Cycle Detection Algorithm (Tortoise & Hare) — treating the array like a linked list to detect a cycle. 👉 Key Learnings: • Arrays can sometimes be visualized as linked structures • Cycle detection is not just for linked lists! • Optimizing for O(1) space is a common interview expectation ⚡ Approach: Use two pointers (slow & fast) First, find intersection point Then, find the cycle start → duplicate number ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) ✅ Successfully passed all test cases! Consistency > Perfection. Let’s keep going 💪 #Day74 #LeetCode #100DaysOfCode #Java #CodingInterview #ProblemSolving #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 77 — Slow & Fast Pointer (Middle of the Linked List) Another day, another clean application of the slow‑fast pointer pattern — this time without cycle detection, just finding the midpoint efficiently. 📌 Problem Solved: - LeetCode 876 – Middle of the Linked List 🧠 Key Learnings: 1️⃣ The Problem Given the head of a singly linked list, return the middle node. If there are two middle nodes (even length), return the second one. 2️⃣ Why Slow‑Fast Pointer Works Here - `slow` moves 1 step at a time. - `fast` moves 2 steps at a time. - When `fast` reaches the end (or `fast.next == null`), `slow` is exactly at the middle. - For even length, `fast` ends at `null` → `slow` points to the second middle node (perfect for this problem’s requirement). 3️⃣ The Code (Simple & Elegant) while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; 4️⃣ Why Not Just Count Then Traverse? - Brute force: count nodes → traverse again → O(n) but two passes. - Slow‑fast pointer achieves the same in one pass with O(1) extra space. 💡 Takeaway: Slow‑fast pointer isn’t only for cycle detection. It’s a versatile tool for: - Finding middle (this problem) - Detecting cycles (LeetCode 141/142) - Finding duplicate numbers (LeetCode 287) - Happy number detection (LeetCode 202) Each problem adds a new dimension to understanding the same pattern. No guilt about past breaks — just showing up, solving, and growing. #DSA #SlowFastPointer #MiddleOfLinkedList #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Day 90 of #100DaysOfCode – Unique Binary Search Trees II Today’s problem was all about generating all structurally unique BSTs for values from 1 to n. At first glance, it feels tricky because it's not just counting trees — we actually need to build every possible tree structure. 💡 Key Insight: Pick each number i as the root Recursively build: Left subtree from [1 ... i-1] Right subtree from [i+1 ... n] Combine every left & right subtree pair 🌳 This is a classic Recursion + Backtracking problem and is closely related to Catalan Numbers. 📌 Example: For n = 3, we get 5 unique BSTs ⚡ What I learned today: How recursion can generate combinations of structures Importance of base case (start > end → null) Combining subproblems effectively 💻 Time Complexity: Approximately O(4ⁿ / √n) Consistency is key — 90 days strong and still going 💪 Next target: 💯 #DSA #Java #LeetCode #Recursion #BinaryTree #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 61 of #100DaysOfCode Solved 101. Symmetric Tree on LeetCode 🔗 🧠 Key Insight: A tree is symmetric if it is a mirror of itself 👉 Left subtree is a mirror of right subtree ⚙️ Approach (Recursive Mirror Check): 1️⃣ Start by comparing: 🔹 root.left and root.right 2️⃣ If both are null → ✅ symmetric 3️⃣ If one is null → ❌ not symmetric 4️⃣ If values differ → ❌ not symmetric 5️⃣ Recursively check mirror condition: 🔹 left.left with right.right 🔹 left.right with right.left 6️⃣ Return: 👉 isMirror(left.left, right.right) && isMirror(left.right, right.left) ⏱️ Time Complexity: O(n) 📦 Space Complexity: O(h) (recursion stack) #100DaysOfCode #LeetCode #DSA #BinaryTree #Recursion #DFS #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