Day - 104 Recover Binary Search Tree The problem - You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant O(1) space solution? Brute Force - Perform inorder traversal to collect all values in an array, identify the two swapped elements, store their positions, traverse the tree again to find and swap them back. This gives O(n) time and O(n) space for storing all node values. Approach Used - •) Declare first (first swapped node), second (second swapped node), prev (previous node in inorder traversal). •) Call helper function, helper(root). •) Swap the values, temp = first.val, first.val = second.val, second.val = temp. Helper Function - helper(TreeNode node) •) If node == null, return. •) Traverse left subtree, helper(node.left). •) If prev != null AND prev.val > node.val, - If first == null, set first = prev. - Set, second = node. •) Update, prev = node. •) Traverse right subtree, helper(node.right). Complexity - Time - O(n), where n is number of nodes. Space - O(h), recursion stack depth. Note - In a valid BST, inorder traversal produces a sorted sequence. When two nodes are swapped, it creates violations where prev.val > current.val. For adjacent swaps, there's one violation; for non-adjacent swaps, there are two. By tracking the first and second violating nodes during inorder traversal, we identify the swapped pair. The algorithm handles both cases by always updating second and only setting first once. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
Recover Swapped Nodes in Binary Search Tree
More Relevant Posts
-
𝐃𝐚𝐲 𝟓𝟓 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem extended the previous one by introducing duplicates in a rotated sorted array. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Minimum in Rotated Sorted Array II 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used modified binary search • Compared nums[mid] with nums[right] Logic: • If nums[mid] > nums[right] → minimum is in right half • If nums[mid] < nums[right] → minimum is in left half (including mid) • If equal → cannot decide, so shrink search space (right--) 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Duplicates can break standard binary search logic • When unsure, safely reduce the search space • Edge cases often define the complexity of the problem • Small changes in conditions can affect performance 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Average Time: O(log n) • Worst Case: O(n) (due to duplicates) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 When the data becomes ambiguous, focus on reducing the problem safely instead of forcing a decision. 55 days consistent 🚀 On to Day 56. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
Day 7 of my #30DayCodeChallenge: Mastering String and Combinatorial Logic! Today, I solved the "Letter Combinations of a Phone Number" problem. The Logic: This problem appears simple but demands efficient logical mapping: 1. Mapping and Initialization: I defined a static array to map phone digits (2-9) directly to their corresponding letter sets. Crucially, the process begins by initializing a base ArrayList with an empty string, which acts as the foundation for the recursive additions. 2. Breadth-First Generation: For each input digit, the algorithm takes the corresponding letters (e.g., 'abc' for '2'). It then performs a double loop: it iterates through all previously generated combinations in the list and appends each new letter to every .ng entry. This new letter to every existing entry. This effectively grows the combinatorial tree level by level. Key Insight: This approach uses an iterative BFS-style expansion instead of standard recursion. It avoids the call-stack overhead, proving that a well-structured loop is often a more powerful (and sometimes faster) alternative for generating combinations. Another challenge completed, another pattern unlocked. The journey continues. #Java #Algorithms #DataStructures #Strings #CombinatorialLogic #150DaysOfCode #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
-
Day 41/75 — Binary Tree Postorder Traversal Today’s problem was about performing postorder traversal of a binary tree. Traversal Order: • Left • Right • Root Approach: • Use recursion • Traverse left subtree • Traverse right subtree • Add current node value Key logic: postorder(root.left); postorder(root.right); res.add(root.val); Time Complexity: O(n) Space Complexity: O(h) (recursion stack, h = height of tree) Key Insight: Tree problems become much simpler when you clearly understand traversal orders. Postorder is especially useful when you need to process children before the parent. 41/75 🚀 #Day41 #DSA #BinaryTree #Recursion #Java #Algorithms #LeetCode
To view or add a comment, sign in
-
-
𝐃𝐚𝐲 𝟓𝟔 – 𝐃𝐒𝐀 𝐉𝐨𝐮𝐫𝐧𝐞𝐲 | 𝐀𝐫𝐫𝐚𝐲𝐬 🚀 Today’s problem focused on finding a peak element using binary search. 𝐏𝐫𝐨𝐛𝐥𝐞𝐦 𝐒𝐨𝐥𝐯𝐞𝐝 • Find Peak Element 𝐀𝐩𝐩𝐫𝐨𝐚𝐜𝐡 • Used binary search instead of linear scan • Compared the middle element with its next element Logic: • If nums[mid] > nums[mid + 1] → peak lies on the left side (including mid) • Else → peak lies on the right side • Continued until left == right 𝐊𝐞𝐲 𝐋𝐞𝐚𝐫𝐧𝐢𝐧𝐠𝐬 • Binary search can be applied on patterns, not just sorted arrays • A peak always exists due to problem constraints • Comparing adjacent elements helps determine direction • Reducing the search space is the key idea 𝐂𝐨𝐦𝐩𝐥𝐞𝐱𝐢𝐭𝐲 • Time: O(log n) • Space: O(1) 𝐓𝐚𝐤𝐞𝐚𝐰𝐚𝐲 Binary search is not about sorted arrays — it’s about eliminating half of the search space using logic. 56 days consistent 🚀 On to Day 57. #DSA #Arrays #BinarySearch #LeetCode #Java #ProblemSolving #DailyCoding #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
-
🔥 Day 552 of #750DaysOfCode 🔥 🔐 LeetCode 2075: Decode the Slanted Ciphertext (Medium) Today’s problem looked tricky at first, but once the pattern clicked, it became super elegant 😄 🧠 Problem Understanding We are given an encoded string that was: Filled diagonally (↘) into a matrix Then read row-wise (→) 👉 Our task is to reverse this process and recover the original text. 💡 Key Insight If encoding is: ➡️ Fill diagonally ➡️ Read row-wise Then decoding is: ➡️ Read diagonally from row-wise string ⚙️ Approach ✅ Step 1: Calculate number of columns cols = encodedText.length() / rows; ✅ Step 2: Traverse diagonals starting from each column for (int startCol = 0; startCol < cols; startCol++) { int row = 0, col = startCol; while (row < rows && col < cols) { result.append(encodedText.charAt(row * cols + col)); row++; col++; } } ✅ Step 3: Remove trailing spaces 🚀 Complexity Time: O(n) Space: O(n) 🧠 What I Learned How to reverse matrix-based encoding patterns Converting 2D traversal → 1D index mapping Importance of pattern recognition in problems 📌 Takeaway Not every problem needs heavy logic. Sometimes, it's just about seeing the pattern correctly 👀 #LeetCode #DSA #Java #CodingJourney #ProblemSolving #Algorithms #SoftwareEngineering #100DaysOfCode #750DaysOfCode
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 98 of construct Binary search Tree from Preorder traversal. The Problem given an Array of Integers preorder, which represents the preorder traversal of BST (i.e., binary search Tree) construct the tree and return it's root guaranteed that there is always possible to find a binary tree with the given requirements for the given taste cases. Brute force - sort the preorder array to get inorder traversal, then use both preorder and inorder arrays to reconstruct the BST) ( like standard tree construction.) this gives O(n log n ) time due to sorting, which is inefficient when BST properties can guide direct construction. Approach used - •) if order. length ==0, return null ( empty tree). •) create root with first element, root = new tree node (Preorder [0]). •) return root. Helper function - insert Treenode root int val) •if val < root. val , insert in left subtree, - if root.left == null, create node , root left = new tree node( val). - Else recurse left , insert (root, left, val). •) Else ( when Val > root Val ), insert in right subtree, - if root. right == null, crate node , root right = new Tree node ( val ) - Else , recurse right , insert ( root. right, val ). complexity Time - O ( n × h ) , where h = height of tree is a number of nodes. Space - O( h), recursion stack depth. Note - preorder traversal's first element is always the root. By leveraging BST insertion rules . ( smaller values go left , larger go right ), we can sequentially insert each element from the preorder array. each insertion automatically finds the correct position building the BST without needing inorder traversal or sorting. #Java #LearnToCode #Problemsolving #DSA #coding
To view or add a comment, sign in
-
-
🔥 Day 364 – Daily DSA Challenge! 🔥 Problem: 🎯 Find K Closest Elements Given a sorted array arr, an integer k, and a target x, return the k closest elements to x in ascending order. 💡 Key Insight — Binary Search on Window Instead of checking each element, we binary search the starting index of a window of size k. Search space: Possible windows → [0 ... n - k] 🧠 Decision Logic At index mid, compare: Distance of left boundary → x - arr[mid] Distance of right boundary → arr[mid + k] - x We choose direction based on: ⚡ Algorithm Steps ✅ Initialize: left = 0, right = n - k ✅ Binary search: If left side is farther → shift right Else → move left ✅ Final window starts at left ✅ Collect k elements ⚙️ Complexity ✅ Time Complexity: O(log(n - k) + k) (binary search + result building) ✅ Space Complexity: O(k) 💬 Challenge for you 1️⃣ Why do we search on window positions instead of elements? 2️⃣ Can you solve this using a heap approach? 3️⃣ What if array was unsorted? #DSA #Day364 #LeetCode #BinarySearch #SlidingWindow #Arrays #Java #ProblemSolving #KeepCoding
To view or add a comment, sign in
-
-
🚀 Day 45/60 – DSA Challenge Today’s problem was about searching in a Rotated Sorted Array using Binary Search 🔍 🔍 Problem Solved: Given a rotated sorted array, efficiently find the index of a target element. 🧠 Approach I Used: Instead of directly applying binary search, I broke the problem into two steps: 1️⃣ Find the pivot (rotation point) using binary search 2️⃣ Apply binary search on the correct half of the array Left half → sorted from start to pivot-1 Right half → sorted from pivot to end ⚡ Key Insight: By identifying the pivot, the problem becomes two simple binary searches Careful boundary checks (like target >= nums[0]) ensure we search in the correct half Handling edge cases (like pivot at index 0) is crucial for correctness 📈 Complexity: Time: O(log n) Space: O(1) 🎯 What I Learned: Complex problems can often be simplified by breaking them into smaller parts Binary Search is not just about searching—it’s about understanding structure Boundary conditions can make or break your solution Debugging edge cases today made the concept even clearer 💡 #Day45 #DSAChallenge #BinarySearch #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
Day 91/100 – LeetCode Challenge ✅ Problem: #98 Validate Binary Search Tree Difficulty: Medium Language: Java Approach: Inorder Traversal with Stack Time Complexity: O(n) Space Complexity: O(h) where h = tree height Key Insight: Inorder traversal of BST produces sorted ascending sequence. Compare each visited node with previous node to detect violations. Solution Brief: Used stack for iterative inorder traversal. Maintained pre pointer to track previous visited node. While traversing: Push all left nodes to stack Pop node, check if root.val <= pre.val (violation) Update pre to current node Move to right subtree #LeetCode #Day91 #100DaysOfCode #Tree #BST #Java #Algorithm #CodingChallenge #ProblemSolving #ValidateBST #MediumProblem #InorderTraversal #Stack #DSA
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