🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gChbc9pi 💡 My thought process: Use an Array to store the values of the tree. The inorder function performs an inorder traversal of the original BST, collecting all node values into a list. Since the inorder traversal of a BST visits nodes in ascending order, the values list is sorted automatically. The buildTree function recursively constructs a balanced BST from a range [left, right] of the sorted values list. The base case returns null when left is greater than right, indicating that the range is empty. For each range, we find the middle index and create a node with values[mid]. This middle element becomes the root of the current subtree. We then recursively build the left subtree using elements from left to mid-1, and the right subtree using elements from mid+1 to right. This method maintains balance because at each level, we split the remaining elements into roughly equal parts. The time complexity is O(n) for the inorder traversal and O(n) for building the tree, resulting in O(n) overall. The space complexity is O(n) for storing values and O(log n) for the recursion stack depth of a balanced tree. 👉 My Solution: https://lnkd.in/gxBj8v6b If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
Reconstructing a Balanced BST from Sorted Array
More Relevant Posts
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g5TWhSTr 💡 My thought process: The idea is to build the binary array recursively while tracking the remaining number of `0`s and `1`s, the last placed element, and the current streak of that element. A state `dp[zero][one][last][cons]` shows how many valid ways there are to form the remaining array when `zero` zeros and `one` ones are left, the previous element was `last`, and it has appeared `cons` times in a row. From each state, the recursion tries to add either `0` or `1`. A `0` can be added if there are remaining zeros and either the last element was different or the consecutive count has not gone over the set `limit`. The same applies when adding `1`. If both counts reach zero, a valid stable array is formed. Memoization saves the result of each state in the `dp` table to prevent recomputing overlapping subproblems. The final result is found by starting the recursion with either `0` or `1` as the first element (if available) and adding up the valid configurations. All computations are done modulo (10^9 + 7) to manage large counts effectively. 👉 My Solution: https://lnkd.in/g8Tr9MEc If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g6C9kJb4 💡 My thought process: For a specific value of k, there are exactly 2^k possible binary strings of that length. For example, if k = 2, the possible binary codes are 00, 01, 10, and 11, making a total of 4 combinations. The solution uses a sliding window approach with size k. It goes through the string using index j and keeps adding characters to a temporary string called window. When the size of the window equals k, the substring is added to an unordered set to ensure it is unique. After adding, the window shifts forward by removing its first character using substr(1), and the process continues. At the end, the function checks if the number of unique substrings stored in the set equals 1 shifted left by k, which represents 2^k. If the sizes match, it means every possible binary substring of length k is in the string, and the function returns true. If not, it returns false. The time complexity is O(n × k) because each substring operation can take up to O(k) time. The space complexity is O(2^k) in the worst case for storing all possible substrings. 👉 My Solution: https://lnkd.in/gBrK8uHB If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
LeetCode Daily | Day 38 🔥 LeetCode POTD – 3714. Longest Balanced Substring II (Medium) ✨ 📌 Problem Insight A substring is balanced if all distinct characters in it appear the same number of times. String contains only 'a', 'b', 'c'. So a balanced substring can have: • 1 distinct character • 2 distinct characters (equal count) • 3 distinct characters (all equal count) 🔍 Approach Instead of one complex solution, split into 3 structured cases: 1️⃣ Mono (Single Character) • Longest consecutive same character • Always balanced 2️⃣ Duo (Two Characters) • Treat one char → +1 • Other char → −1 • Use prefix sum + hashmap • Reset when third character appears 👉 If two prefixes have same delta → equal count substring found. 3️⃣ Trio (Three Characters) • Maintain counts of a, b, c • Track (b−a, c−a) differences • If same pair appears again → balanced substring 👉 Same prefix-difference trick, extended to 2D. 💡 Why This Works Balanced condition reduces to: • For 2 chars → equal frequency • For 3 chars → equal pairwise differences Prefix differences repeating ⇒ middle substring is balanced. Breaking problem into structural cases simplifies implementation. ⏱ Complexity Time: O(n log n) (due to map) Space: O(n) (Can be optimized to O(n) using unordered_map) 🧠 Pattern Used Prefix Sum | Hashing | Difference Tracking | Case-Based Decomposition Clean structure > complicated logic. Hard part isn’t idea — it’s handling all cases correctly. Consistency over motivation — one problem a day 🚀 #LeetCode #DSA #PrefixSum #Hashing #Cplusplus #CodingDaily #Consistency
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/grkpkPnR 💡 My thought process: The approach uses a greedy strategy. First, for each row in the grid, we count the number of trailing zeros by scanning from the last column to the left until we encounter a 1. We store these counts in a separate array called endZero because only the number of trailing zeros matters for checking whether a row meets the upper triangular condition. For a valid grid, at row index i, we must ensure there are at least n - i - 1 trailing zeros. This way, all elements above the main diagonal can remain zero. We go through each row from top to bottom. If the current row has enough trailing zeros (endZero[i] >= n - i - 1), we proceed to the next row. If not, we look below for the nearest row that meets the requirement. If we cannot find such a row, arranging the grid is impossible, so we return -1. If we do find a valid row, we simulate adjacent row swaps by continually swapping it upward until it reaches position i, counting each swap. This method ensures we use the minimum number of swaps by always choosing the closest valid row. 👉 My Solution: https://lnkd.in/gK4-jM2B If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/g4J85qey 💡 My thought process: If you have a block of three 0s followed by a block of two 1s (00011), you can only create two valid pairs: 01 and 0011. The smaller group always limits the number of matches you can make, which is why the code uses min(prev, curr). To keep track of this, the code uses prev for the size of the block you just finished and curr for the block you’re currently counting. As you go through the string, you keep increasing curr as long as the characters remain the same. The moment the character changes, like when you hit a 1 after a series of 0s, it means you've completed a block. You take the min of the old block and the new block, add it to your total, move the curr count into prev, and start over for the next group. There is one small issue in the code: because that addition only happens when the characters change, the very last block in the string doesn't get processed inside the loop. That’s why there is one extra result += min(prev, curr) at the very end to catch that final transition. 👉 My Solution: https://lnkd.in/gdK35f76 If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
Day 58/100 – #100DaysOfLeetCode 🚀 🧩 Problem: LeetCode 696 – Count Binary Substrings (Medium) 🧠 Approach: For each transition, add min(previous_group_length, current_group_length) to the result. This ensures equal numbers of consecutive 0s and 1s in each valid substring. 💻 Solution: class Solution: def countBinarySubstrings(self, s: str) -> int: prev = 0 curr = 1 result = 0 for i in range(1, len(s)): if s[i] == s[i-1]: curr += 1 else: result += min(prev, curr) prev = curr curr = 1 result += min(prev, curr) return result ⏱ Time | Space: O(n) | O(1) 📌 Key Takeaway: Tracking group lengths instead of generating substrings makes the solution efficient and avoids unnecessary extra space. #leetcode #dsa #development #problemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 LeetCode Daily Challenge 🔗 Problem: https://lnkd.in/gXwweaP3 💡 My thought process: This solution finds the longest substring where the characters 'a', 'b', and 'c' appear the same number of times. It approaches the problem by breaking it into three separate cases: substrings with one character, substrings with two distinct characters, and substrings with all three characters. In the single-character case, the method scans the string and tracks the length of the longest continuous run of the same character. This addresses substrings where balance is easily met, as only one character is present. For the two-character case, the technique uses a prefix-difference approach. While scanning the string, it counts the two selected characters and calculates their difference. If the same difference has occurred before, the segment between the last index and the current index must have equal counts of the two characters, making its length a valid option. When a third character appears, it resets the counts and the hash map to prevent invalid matches across segments. In the three-character case, the prefix concept is extended to two dimensions. Instead of tracking one difference, the algorithm focuses on two differences: (count(a) − count(b)) and (count(a) − count(c)). If the pair of differences appears again, it indicates that the counts of all three characters between those indices are equal, creating a balanced substring. A hash map keeps the earliest index for each difference pair, allowing for quick length updates in a single pass through the string. 👉 My Solution: https://lnkd.in/gc_vMxFG If you found this breakdown helpful, feel free to ⭐ the repo or connect with me on LinkedIn 🙂🚀 #️⃣ #leetcode #cpp #dsa #coding #problemsolving #engineering #BDRM #BackendDevWithRahulMaheswari
To view or add a comment, sign in
-
-
#55 🚀 Solved: Longest Palindromic Substring (Optimized Approach) | LeetCode Today I worked on the Longest Palindromic Substring problem in C++ and improved my initial brute-force solution to a more efficient approach. 🔎 Problem: Given a string s, return the longest palindromic substring. 💡 My Learning Journey: ✅ Step 1: Brute Force Approach Checked all possible substrings Verified each substring using a palindrome function Time Complexity: O(n³) It worked… but wasn’t efficient for large inputs. 🚀 Step 2: Optimized – Expand Around Center Instead of checking all substrings, I treated every character as a potential center and expanded outward. Handled: Odd-length palindromes (center at one character) Even-length palindromes (center between two characters) 📈 Final Complexity: Time: O(n²) Space: O(1) (No extra DP table) 📚 Key Takeaways: Always start with brute force to understand the problem. Then optimize step by step. Avoid unnecessary string copies (use const string&). Think in terms of patterns (palindromes expand symmetrically). Every problem teaches more than just syntax — it improves problem-solving thinking 🧠 #LeetCode #DSA #CPP #ProblemSolving #CodingJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 526 of #750DaysOfCode 🚀 Today I solved LeetCode 3129 – Find All Possible Stable Binary Arrays I. 🔹 Problem Summary We are given three integers: zero, one, and limit. We need to count the number of binary arrays that: • Contain exactly zero number of 0s • Contain exactly one number of 1s • Do not allow more than limit consecutive identical elements In other words, every subarray longer than limit must contain both 0 and 1, preventing long runs of the same digit. 🔹 Approach I solved this using Dynamic Programming. Idea: Track how many zeros and ones are used. Maintain the last placed digit (0 or 1). Ensure the count of consecutive digits never exceeds the limit. Use DP states to count valid configurations and apply modulo (10^9 + 7) for large results. 🔹 Key Concepts Practiced Dynamic Programming State transitions Handling constraints with limit on consecutive elements Modular arithmetic 💡 Problems like this strengthen DP intuition and constraint handling, which are very common in coding interviews. Consistency continues… 🔥 #leetcode #dsa #dynamicprogramming #codingchallenge #softwareengineering #programming #developers #learninginpublic #techjourney #750daysofcode
To view or add a comment, sign in
-
-
#100DaysOfLeetCodeChallenge Day 17/100-LeetCode Challenge 876-MIDDLE-OF-THE-LINKED LIST. 🧩 Problem Statement Given the head of a singly linked list, return the middle node. If there are two middle nodes, return the second middle node. 💡 My Approach I used a basic and clear approach: 1️⃣ First traversal → Count total nodes. 2️⃣ Calculate count / 2. 3️⃣ Second traversal → Move to that position. 4️⃣ Return the middle node. 🛠 Why I Used This Approach? ✅ Easy to understand ✅ Beginner-friendly ✅ No complex pointer logic ✅ Clean O(1) space solution Master basics first, then optimize 🔥 #LeetCode #DSA #LinkedList #ProblemSolving #100DaysOfCode #CodingJourney
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