🚀 Day 123 of #LeetCode Challenge! Problem: Convert Sorted Array to Binary Search Tree 💡 My Approach: The task is to convert a sorted array into a height-balanced BST — meaning the depth of the two subtrees of every node should not differ by more than one. Here’s how I approached it: Pick the middle element of the array as the root (ensures balance). Recursively build the left subtree from the left half. Recursively build the right subtree from the right half. This method ensures the tree is balanced and follows the BST property (left < root < right). 🧠 Key Idea The midpoint of the current range always becomes the root, making the BST height-balanced naturally. ✨ Example Input: nums = [-10, -3, 0, 5, 9] Output: A balanced BST like: 0 / \ -3 9 / / -10 5 ⏱ Complexity TypeValueTimeO(N) — each element is processed onceSpaceO(log N) — recursion stack (for balanced BST) 📎 GitHub Link: https://lnkd.in/gDkzKT6A #LeetCode #BinarySearchTree #Recursion #C++ #ProblemSolving #DSA #Day123 #CodingChallenge
How to Convert a Sorted Array to a Balanced BST in C++
More Relevant Posts
-
🚀Day 113 of #LeetCode Challenge! Problem: Search in a Binary Search Tree 🌳 My Approach: Since this is a Binary Search Tree (BST), we can use the BST property: If the value we are searching is less than the current node’s value → search in the left subtree. If it is greater → search in the right subtree. Continue until we either find the node or reach a NULL pointer. ✨ Example: Input: root = [4,2,7,1,3], val = 2 Output: [2,1,3] Explanation: The subtree rooted at value 2 is returned. ⏱ Time Complexity: O(h) — where h is the height of the tree 📦 Space Complexity: O(h) — recursive call stack 📌 Key Insight: BST property helps us efficiently go left or right — no need to search the entire tree! 👨💻 GitHub Link: https://lnkd.in/gz6UmG6y #LeetCode #BinarySearchTree #TreeTraversal #Recursion #ProblemSolving #DSA #CodingChallenge #C++ #Day113
To view or add a comment, sign in
-
-
🚀 Day 112 of #LeetCode Challenge! Problem: Diameter of Binary Tree 💡 My Approach: The diameter of a binary tree is the longest path between any two nodes (may or may not pass through the root). The trick is to calculate the height of each subtree while keeping track of the maximum left + right path encountered. Use a helper function height() that: Recursively computes left and right subtree heights. Updates the global diameter as the maximum sum of left and right heights. ✨ Example: Input: [1,2,3,4,5] Output: 3 Explanation: The longest path is [4,2,1,3] or [5,2,1,3] ⏱ Time Complexity: O(N) — visit every node once 💾 Space Complexity: O(H) — recursive stack (H = height of tree) 🌱 Key Insight: At each node, the longest path through it is leftHeight + rightHeight. The overall diameter is the maximum of all such paths. 👨💻 GitHub Link: https://lnkd.in/dvUDMZUC #LeetCode #BinaryTree #Recursion #TreeTraversal #DSA #CodingChallenge #C++ #Day112
To view or add a comment, sign in
-
-
🚀 Day 124 of #LeetCode Challenge! Problem: Binary Tree Inorder Traversal 💡 My Approach: The goal is to perform an inorder traversal of a binary tree — visiting nodes in the order: Left → Root → Right. Here’s how I implemented it: Use recursion to traverse the tree. Start from the root node. Recursively visit the left subtree, then record the root value, and finally traverse the right subtree. This ensures all nodes are visited in sorted order for a BST. ✨ Example Input: [1, null, 2, 3] Output: [1, 3, 2] 🧠 Key Idea Inorder traversal naturally retrieves nodes in ascending order if the tree is a Binary Search Tree (BST). ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gBgJShhT #LeetCode #BinaryTree #InorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day124
To view or add a comment, sign in
-
-
💻 Day 47 of #50DaysOfLeetCode Challenge 🚀 Problem: Binary Tree Maximum Path Sum (Leetcode 124) The goal was to find the maximum path sum in a binary tree — where the path can start and end at any node, not just the root. 🌲 🧠 Approach: I solved it using postorder traversal (Left → Right → Root). At every node, I calculated: 1️⃣ bothpaths → path passing through root (left + right + root) 2️⃣ bestpath → best path going downward from root (max of left or right + root) 3️⃣ onlyroot → when only the root node is part of the path At each step, I updated a global maxsum with the best of these three values. This way, every node contributed the maximum possible sum considering all cases. 🧩 Key Takeaway: 👉 Always think in terms of "What value should I return to parent?" vs "What value should I update globally?" 👉 Binary tree recursion becomes intuitive once you separate these two thoughts.
To view or add a comment, sign in
-
-
🚀 Day 122 of #LeetCode Challenge! Problem: Subtree of Another Tree 💡 My Approach: The goal is to check whether one tree (subRoot) is a subtree of another (root). Here’s how I approached it: Traverse the main tree (root) recursively. At each node, check if the subtree starting there is identical to subRoot. If not, keep checking in the left and right subtrees. For the comparison, a helper function isSameTree() ensures both trees have identical structure and node values. 🧠 Key Idea A tree subRoot is a subtree of root if there exists a node in root such that the subtree rooted at that node is structurally identical to subRoot. ✨ Example Input: root = [3,4,5,1,2] subRoot = [4,1,2] Output: ✅ true Explanation: The subtree starting at node 4 in root matches subRoot. ⏱ Complexity TypeValueTimeO(M × N) — for each node in root, we may compare with all nodes in subRootSpaceO(H) — recursion stack (H = height of the tree) 📎 GitHub Link: https://lnkd.in/gv3w8RFe #LeetCode #BinaryTree #Recursion #C++ #ProblemSolving #Day122 #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 125 of #LeetCode Challenge! Problem: Binary Tree Preorder Traversal 💡 My Approach: The goal is to perform a preorder traversal of a binary tree — visiting nodes in the order: Root → Left → Right Here’s the step-by-step logic: Start from the root node. Visit (record) the root value first. Recursively traverse the left subtree, then the right subtree. Store values in a vector as you go. ✨ Example Input: [1, null, 2, 3] Output: [1, 2, 3] 🧠 Key Idea Preorder traversal is useful when you need to copy or serialize a tree — it captures the structure starting from the root. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gZ6GeXzm #LeetCode #BinaryTree #PreorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day125
To view or add a comment, sign in
-
-
🚀 Day 127 of #LeetCode Challenge! Problem: Binary Tree Level Order Traversal 💡 My Approach: This problem involves traversing the binary tree level by level — also known as Breadth-First Search (BFS) traversal. Here’s the step-by-step breakdown: Use a queue to store nodes level by level. For each level, store all node values in a temporary list. Push their left and right children into the queue. After finishing one level, add it to the result vector. ✨ Example Input: [3,9,20,null,null,15,7] Output: [[3], [9,20], [15,7]] 🧠 Key Idea This traversal captures the hierarchical structure of the tree perfectly — often used in problems involving level-based processing, like Zigzag traversal or average of levels. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(N) — for queue and result storage 📎 GitHub Link: https://lnkd.in/gntMrKbU #LeetCode #BinaryTree #BFS #LevelOrderTraversal #DSA #ProblemSolving #C++ #CodingChallenge #100DaysOfCode #Day127
To view or add a comment, sign in
-
-
Day 22 of #100DaysOfCode Today I solved the “Permutation in String” problem on LeetCode — a tricky one that really sharpens your understanding of sliding window and frequency mapping in strings. 🧩 Problem in short: Given two strings s1 and s2, the task is to check if any permutation of s1 exists as a substring in s2. At first glance, it feels like a brute-force problem — generate all permutations of s1 and check each in s2. But that’s computational suicide for longer strings. So the challenge was to find a smarter, optimized approach. ⚙️ Intuitive Approach: Instead of generating permutations, I focused on character frequencies. Maintain two frequency arrays — one for s1 and one for the current window of s2. Slide the window across s2, adding and removing characters as you move. Whenever both frequency arrays match, it means that substring of s2 is a permutation of s1. This approach reduces the complexity drastically and relies on pattern recognition through frequency matching, not brute force. Every day in this challenge is a reminder that optimization isn’t about doing less work — it’s about doing the right work. #LeetCode #C++ #ProblemSolving #DSA #CodingJourney #100DaysOfCode
To view or add a comment, sign in
-
-
🌟 Day 117 of 150 – Find Peak Element [LeetCode 162] 🌟 🔧 Problem Brief: You are given an integer array nums[], where a peak element is one that is strictly greater than its neighbors. Your task → Return the index of any peak element. You may assume that elements outside the array are -∞, i.e., nums[-1] = nums[n] = -∞. 🎯 Goal: Find any peak element using a binary search approach in O(log n) time ⏱. 🧠 How We Solve It? → Binary Search on Slopes 1️⃣ Initialize two pointers: left = 0, right = nums.length - 1 2️⃣ While left < right: Compute middle index → mid = (left + right) / 2 Compare middle element with its next neighbor: If nums[mid] > nums[mid + 1] → we are on a descending slope, so move left → right = mid Else → we are on an ascending slope, so move right → left = mid + 1 3️⃣ When the loop ends, left == right — this index is guaranteed to be a peak. 🧩 Example Walkthrough 📥 Input: nums = [1, 2, 3, 1] 📘 Steps: Start: left = 0, right = 3 mid = 1 → nums[mid]=2, nums[mid+1]=3 → ascending → left = 2 mid = 2 → nums[mid]=3, nums[mid+1]=1 → descending → right = 2 ✅ Output: 2 (index of peak element 3) 🧮 Complexity Analysis ⏱ Time Complexity: O(log n) 💾 Space Complexity: O(1) 📎 GitHub Link: https://lnkd.in/e5kCCFJY #Day117 #LeetCode #FindPeakElement #BinarySearch #JavaDSA #ProblemSolving #CodingChallenge #InterviewPrep #TechWithSaravana #150DaysOfCode #DSA #LearningJourney #CodeEveryday #Algorithm
To view or add a comment, sign in
-
3354. Make Array Elements Equal to Zero 🧩 LeetCode Problem of the Day — Solved! 🔗 Solution Link: https://lnkd.in/gEMu6GfF Today’s problem really tested my patience 😅. I got the core idea pretty early — I thought using prefix sums would easily handle it. My logic was that if the sum on the left and right of an index are equal, we can increment the result by 2. Seemed straightforward, right? Well… my first submission failed. 😐 After spending around 20 minutes decoding the example and carefully analyzing edge cases, I realized I’d missed just one condition — checking if the difference equals 1. Adding that made everything work perfectly! 🧠 Key Idea: Use prefix sums to calculate cumulative sums efficiently. For each index where nums[i] == 0: If left and right sums are equal → add 2. If their absolute difference is 1 → add 1. 🕒 Complexity: Time: O(n) Space: O(n) 💡 Takeaway: Even “easy” problems can surprise you — sometimes it’s that one missing condition that makes all the difference. Always test edge cases before finalizing! #LeetCode #ProblemOfTheDay #DSA #EasyProblem #CodingJourney #PrefixSum #Debugging #Consistency #LearningByDoing
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