Continuing my 100 Days of DSA journey. Day 69 — LeetCode (Balanced Binary Tree) Balanced Binary Tree – Given a binary tree, determine if it is height-balanced (i.e., the heights of left and right subtrees of every node differ by no more than 1). Approach (DFS + Height Optimization): a) Use a recursive function to calculate the height of each subtree b) For each node, recursively get the height of left and right subtrees c) If any subtree returns -1, propagate -1 upwards (indicating imbalance) d) Check if the absolute difference between left and right heights is greater than 1 e) If unbalanced, return -1 immediately f) Otherwise, return 1 + max(leftHeight, rightHeight) Time Complexity: O(n) Space Complexity: O(h) (recursion stack) On to Day 70... #100DaysOfCode #DSA #LeetCode #Cpp #Algorithms #CodingJourney #ProblemSolving #SoftwareEngineering #InterviewPrep #LearningInPublic #geeksforgeeks #Microsoft #Greedy #Strings #Optimization
Balanced Binary Tree LeetCode Solution
More Relevant Posts
-
🚀 Day 15 of my DSA Grind Sometimes the best way to optimize a Sliding Window problem is to not use a window at all! Today, I tackled a LeetCode Medium that completely changed how I look at substring counting. 🔹 Number of Substrings Containing All Three Characters (LC 1358): The standard approach here is using a left and right pointer to expand and shrink a window until it contains 'a', 'b', and 'c'. But managing those pointers can get messy. The Breakthrough: I scrapped the traditional window and used the "Last Seen" Index array. I simply tracked the exact index where I most recently saw an 'a', a 'b', and a 'c'. The Math: To form a valid substring ending at my current position, I just need to reach back to the minimum of those three indices. Every single index before that minimum is a valid starting point! The Result: By applying the formula count += 1 + min(last_a, last_b, last_c), I reduced the problem to a single, lightning-fast O(N) pass with strict O(1) space. Zero nested loops, zero pointer rewinding! #DataStructures #Algorithms #LeetCode #CPP #ProblemSolving #SoftwareEngineering #PlacementPreparation #Optimization #100DaysOfCode #TechJourney
To view or add a comment, sign in
-
-
Continuing my 100 Days of DSA journey. Day 76 — LeetCode (Minimum Window Substring) - Hard Minimum Window Substring – Given two strings s and t, return the minimum window in s which will contain all the characters in t. If there is no such window, return an empty string. Approach (Sliding Window + Hashing): a) Use two hash maps to track required characters and current window frequency b) Maintain two pointers to represent the window (left and right) c) Expand the window by moving the right pointer and update frequency d) Keep track of how many required characters are satisfied e) When all characters are matched, try to shrink the window from the left f) Update the minimum window length whenever a valid window is found g) Continue the process until the entire string is traversed Time Complexity: O(n) Space Complexity: O(1) Key takeaway: Learned how combining sliding window with frequency tracking helps efficiently solve complex substring problems with multiple constraints. On to Day 77... #100DaysOfCode #DSA #LeetCode #Cpp #CyclicSort #Algorithms #CodingJourney #ProblemSolving #SoftwareEngineering #InterviewPrep #LearningInPublic #geeksforgeeks #Microsoft #SlidingWindow #Hashing #Strings #TwoPointers
To view or add a comment, sign in
-
-
Continuing my 100 Days of DSA journey. Day 71 — LeetCode (Valid Parentheses) Valid Parentheses – Given a string containing just '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A string is valid if open brackets are closed by the same type and in the correct order. Approach (Stack): a) Use a stack to keep track of opening brackets b) Traverse the string character by character c) If an opening bracket is encountered, push it onto the stack d) If a closing bracket is found: Check if the stack is empty → if yes, return false Otherwise, compare with the top of the stack If it matches the corresponding opening bracket, pop it Else, return false e) At the end, if the stack is empty → valid, otherwise invalid Time Complexity: O(n) Space Complexity: O(n) Key takeaway: Learned how stack helps in handling nested and ordered structures efficiently, especially in problems involving matching pairs. On to Day 72... #100DaysOfCode #DSA #LeetCode #Cpp #CyclicSort #Algorithms #CodingJourney #ProblemSolving #SoftwareEngineering #InterviewPrep #LearningInPublic #geeksforgeeks #Microsoft #Stack #Strings #Parentheses #DataStructures
To view or add a comment, sign in
-
-
Day 181/365 – DSA Challenge 🌊 Solved Surrounded Regions on LeetCode today. 🔹 Problem: Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. 👉 Replace all 'O' that are completely surrounded with 'X'. 🔹 Approach Used: DFS (Boundary Traversal) 💡 Key Idea: Any 'O' connected to the boundary can never be surrounded. Steps: 1️⃣ Traverse all boundary cells 2️⃣ Run DFS on boundary 'O' → mark them as safe 3️⃣ Traverse entire board: Unvisited 'O' → convert to 'X' Visited 'O' → keep as it is 🔹 Why this works? We avoid checking every region individually. Instead, we eliminate all safe regions first — much more efficient. 🔹 Time Complexity: O(m × n) 🔹 Space Complexity: O(m × n) (visited + recursion stack) 🔹 Concepts Used: DFS, Graph Traversal, Matrix Boundary Logic 🔥 Pattern Recognized: This is similar to problems like Number of Islands — but in reverse thinking (protect instead of count). 💻 Language: C++ Clean logic + strong intuition problem 🚀 #Day181 #365DaysOfCode #DSA #LeetCode #Graphs #DFS #CodingJourney #Cpp
To view or add a comment, sign in
-
-
🚀 Day 7/100 – Strengthening DSA with Array & Binary Search Today I focused on improving my problem-solving skills by practicing array-based problems on LeetCode. 💻 What I solved today: 1️⃣ Search Insert Position Used Binary Search Reduced time complexity to O(log n) Learned how to find correct position even if element is not present 2️⃣ Remove Element Used in-place array modification Optimized space complexity to O(1) Learned efficient element removal without extra memory 📊 Progress Update: Solved: 7 problems (Arrays) Focusing on building strong DSA fundamentals step by step 🧠 Key Learning: ✔ Binary Search is one of the most powerful techniques for optimization ✔ In-place operations help reduce space complexity ✔ Small problems build strong logic for bigger challenges 🎯 Focus Going Forward: Practice more array patterns Move towards medium-level problems Improve speed & accuracy Consistency is the key — one problem at a time 💪 #Day7 #100DaysOfLearning #DSA #LeetCode #Arrays #BinarySearch #ProblemSolving #CodingJourney
To view or add a comment, sign in
-
-
🚀 𝗬𝗼𝘂 𝗰𝗼𝗺𝗽𝗿𝗲𝘀𝘀 𝟭𝟬 𝗚𝗕, 𝗴𝗲𝘁 𝟯 𝗚𝗕. 𝗬𝗼𝘂 𝗲𝘅𝘁𝗿𝗮𝗰𝘁, 𝗴𝗲𝘁 𝟭𝟬 𝗚𝗕 𝗯𝗮𝗰𝗸. 𝗪𝗵𝗲𝗿𝗲 𝗱𝗶𝗱 𝘁𝗵𝗼𝘀𝗲 𝟳 𝗚𝗕 𝗲𝘃𝗲𝗻 𝗴𝗼? Your file is full of repetition. Way more than you think. A video? Thousands of frames where the background doesn't change. A text file? The word "the" showing up hundreds of times. Code? Same patterns everywhere. The first algorithm, 𝗟𝗭𝟳𝟳, catches this. Instead of storing "the" for the 300th time, it leaves a tiny note - "copy what I wrote 200 bytes ago." That note is 3 bytes. The original was 50. Gone. Then 𝗛𝘂𝗳𝗳𝗺𝗮𝗻 steps in and looks at what's left. It notices some symbols appear constantly, others barely show up. So it gives short codes to the popular ones, longer codes to the rare ones. Like VIP lanes, frequent flyers board faster. Boom. 10 GB becomes 3 GB. Now extraction, The ZIP file secretly carries a codebook inside it. When you extract, it reads that map and works backwards. Huffman restores every symbol. LZ77 follows every pointer and pastes everything back. Byte by byte. Frame by frame. Pixel by pixel. Your original 10 GB, fully restored. Math didn't compress your file. Math just found a smarter way to tell the same story. #SoftwareEngineering #ComputerScience #Programming #TechForEveryone #LearningInPublic #Algorithms #Developer #CodingLife
To view or add a comment, sign in
-
Phone Letter Combinations Using Backtracking Day 8 👈 👉 Given a digit string, generate all possible letter combinations based on phone keypad mapping. 💡 Key learnings: -- This is a backtracking pattern problem -- At each step, we pick a character from the mapped letters -- Build the string step by step and explore all possibilities -- Base condition: when the path length matches input length 🔁 Approach: -- Map digits to characters -- Use recursion to build combinations -- Backtrack by removing the last character after each call #DSA #Backtracking #Algorithms #CodingJourney #LeetCode #ProblemSolving #SoftwareEngineer #InterviewPreparation #LearningInPublic #Recursion
To view or add a comment, sign in
-
-
DSA Journey | Stack Decode String 1.Traverse the string and push characters into the stack. 2.When ] is encountered, start forming the substring until [ is found. 3.Remove [ and then extract the number (can be multi-digit). 4.Repeat the substring k times and push it back to the stack. 5.Continue this process to handle nested patterns automatically. 6.At the end, build the final decoded string from the stack.
To view or add a comment, sign in
-
-
Day 170/365 – DSA Challenge 🚀 Solved Convert Sorted Array to Binary Search Tree on LeetCode today. 🔹 Problem: Given a sorted array, convert it into a height-balanced Binary Search Tree (BST). 🔹 Approach Used: Recursion (Divide & Conquer) Steps followed: 1️⃣ Pick the middle element of the array → root 2️⃣ Recursively build: Left subtree from left half Right subtree from right half 3️⃣ Repeat until subarray becomes empty 🔹 Key Idea: Choosing the middle element ensures balance of the BST. 🔹 Time Complexity: O(n) 🔹 Space Complexity: O(log n) (recursion stack) 💻 Language: C++ A clean and elegant problem that strengthens BST properties + recursion intuition. #Day170 #365DaysOfCode #DSA #LeetCode #BinaryTree #BST #Recursion #CodingChallenge #Cpp
To view or add a comment, sign in
-
-
🚀 Day 96 of 100 Days of DSA 📌 LeetCode #3 (Longest Substring Without Repeating Characters) 📈 "Consistency over motivation, Progress over perfection" A classic problem that introduces one of the most important techniques in DSA: Sliding Window. 🧩 Problem Statement Given a string s: Find the length of the longest substring without repeating characters Important: • Substring must be continuous • Characters must be unique 🧠 Thought Process Initial idea: Generate all substrings Check if each has unique characters But quickly: ⚠️ Too many substrings → inefficient Needed: A way to dynamically maintain a valid substring 🚫 Brute Force Approach 1. Generate all substrings 2. For each substring: • Check for duplicates using a set Complexity: • Substrings → O(n²) • Checking uniqueness → O(n) Overall → O(n³) ❌ 🔄 Better Approach (Set + Sliding Window) 1. Use two pointers (left, right) 2. Expand window 3. If duplicate found → shrink from left Improves to: O(n) time But still involves repeated removals. 🔍 Key Insight Instead of removing characters one by one: Directly jump the left pointer How? Store the last seen index of each character ✅ Approach Used Optimized Sliding Window + Last Seen Index ⚙️ Strategy 1. Maintain: • left → start of window • right → current index • lastSeen → last index of each character 2. For each character: • If seen before within window → move left • Update last seen index • Calculate current window length 3. Track maximum length 💡 Intuition Think of a moving window: Expand when characters are unique Jump forward when duplicate appears No unnecessary backtracking. ⏱ Complexity Analysis Time Complexity: O(n) Each character processed once Space Complexity: O(1) (Fixed character set) 💡 Key Learnings - Sliding window is powerful for substring problems - Avoid recomputation using memory (hashing/indexing) - Moving pointers intelligently reduces complexity - Substring problems often require dynamic window resizing #100DaysOfDSA #Day96 #LeetCode #SlidingWindow #Strings #Algorithms #DSA #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