Day 50: Binary Search Tree Iterator (BST) 🌲 I'VE HIT THE HALFWAY MARK! Day 50 of #100DaysOfCode is dedicated to mastering the "Binary Search Tree Iterator." This challenge requires designing a class that enables in-order traversal of a BST using constant time complexity for the key operations. The key insight is using an Iterative Inorder Traversal with a Stack: __init__ (Initialization): The constructor doesn't traverse the whole tree. It uses a helper function (_push_left) to initially push the root and all its left descendants onto the stack. This positions the stack to start at the smallest element. next(): This method retrieves the next smallest element. It simply pops the top element from the stack, and then immediately checks if that popped node has a right child. If it does, it calls _push_left on the right child to load the next set of smallest elements onto the stack. Efficiency: The design ensures that while an element is pushed and popped exactly once overall (O(n) total time), the amortized time complexity for both next() and hasNext() is O(1). This was a perfect problem to mark the halfway point—combining Data Structures and Algorithmic Design! #Python #DSA #Algorithms #BST #Iterator #Stack #100DaysOfCode
Mastering Binary Search Tree Iterator in Python
More Relevant Posts
-
Day 62: Recover Binary Search Tree (BST) 🌳 I'm continuing my journey on Day 62 of #100DaysOfCode with a challenging BST problem: "Recover Binary Search Tree." The task is to fix a BST where exactly two nodes have been swapped by mistake, all without changing the tree's structure. The key insight relies on the property of Inorder Traversal of a BST, which always yields nodes in ascending order. Inorder Traversal: I first perform a standard inorder traversal (using recursion) to store the node values in an ascending list (inorder). Finding Swapped Nodes: I then iterate through the inorder list to find the two misplaced nodes. A violation occurs when inorder[i-1] > inorder[i]. The first misplaced node (first) is the larger element of the first violation. The second misplaced node (second) is the smaller element of the last violation. Correction: Finally, I swap the values of the two nodes found in the original tree. This method achieves an O(n) time complexity and O(n) space complexity (due to storing the inorder array). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #BST #InorderTraversal #100DaysOfCode #ProblemSolving
To view or add a comment, sign in
-
-
🌳 DSA Challenge – Day 99 Problem: Balanced Binary Tree ⚖️🌲 This classic tree problem tests your understanding of recursion, depth-first search, and how to efficiently check balance conditions in binary trees. 🧠 Problem Summary: A height-balanced binary tree is one in which the height of the two subtrees of every node never differs by more than 1. Your task: Given the root of a binary tree, determine whether it is height-balanced. ⚙️ My Approach: 1️⃣ Use a recursive DFS helper util() to traverse the tree. 2️⃣ For each node, compute: Whether its left and right subtrees are balanced. The maximum depth of its left and right subtrees. 3️⃣ If at any point the height difference exceeds 1, return False. 4️⃣ The function returns both a boolean (isBalanced) and an integer (height). 💡 Optimization Insight: Instead of computing the height in a separate pass (which would make it O(n²)), this approach combines balance checking and height calculation in one DFS traversal, resulting in O(n) time complexity. 📈 Complexity Analysis: Time Complexity: O(n) — Each node is visited once. Space Complexity: O(h) — Recursion stack, where h is the height of the tree. ✨ Key Takeaway: Efficient recursion patterns often come from returning multiple values — combining partial results avoids redundant computation and keeps solutions elegant. 🔖 #DSA #100DaysOfCode #BinaryTree #LeetCode #ProblemSolving #CodingChallenge #Python #Algorithms #Recursion #TreeTraversal #TechCommunity #LearningEveryday
To view or add a comment, sign in
-
-
#LLMHolywarChronicles The SWE-ReBench leaderboard was updated yesterday with 51 new tasks from October. For anyone who hasn’t been following: the team pulls recent PRs from Python repositories that meet certain criteria and evaluates them with a simple agent across different models. Sonnet 4.5 is still in the lead… but I won’t repeat the whole article here (https://swe-rebench.com/ ); feel free to read it if you’re interested. The only thing really worth highlighting is this: “* MiniMax M2 is the most cost-efficient open-source model among the top performers. Its pricing is $0.255 / $1.02 per 1M input/output tokens, whereas gpt-5-codex costs $1.25 / $10.00– with cached input available at just $0.125. In agentic workflows, where large trajectory prefixes are reused, this cache advantage can make models with cheap cache reads more beneficial even if their raw input/output prices are higher. In case of gpt-5-codex, it has approximately the same Cost per Problem as MiniMax M2 ($0.51 vs $0.44), being yet much more powerful.”
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 89 Problem: Subsets II (Handling Duplicates in Power Set) ⚙️✨ This problem was a great exploration of recursion, backtracking, and how to systematically avoid duplicate subsets using careful pruning. 🧠 Problem Summary: You are given an integer array nums that may contain duplicates. Your goal: return all possible subsets (the power set) without including any duplicate subsets. ⚙️ My Approach: 1️⃣ First, sort the array — this step helps group duplicates together, which is crucial for skipping them efficiently. 2️⃣ Use recursive backtracking to explore all possible inclusion/exclusion combinations. 3️⃣ Whenever a duplicate element is found (i.e., nums[i] == nums[i-1]), skip it if it’s at the same recursion depth — ensuring unique subset generation. 4️⃣ Keep track of the current subset and add a copy to the result whenever we reach a new state. 📈 Complexity: Time: O(2ⁿ) → Each element can be either included or excluded. Space: O(n) → For recursion and temporary subset storage. ✨ Key Takeaway: Sorting before recursion is often the simplest way to handle duplicates in backtracking problems. With one small condition check, you can turn exponential chaos into structured exploration. ⚡ 🔖 #DSA #100DaysOfCode #LeetCode #ProblemSolving #Recursion #Backtracking #Algorithms #CodingChallenge #Python #TechCommunity #InterviewPrep #EfficientCode #LearningByBuilding #CodeEveryday
To view or add a comment, sign in
-
-
🚀 Day 29 DSA Challenge – Problem 704: Binary Search A timeless classic — the foundation of efficient searching algorithms 🔍 🎯 Problem Statement: Given a sorted array nums and an integer target, find the index of target using an algorithm with O(log n) time complexity. If target doesn’t exist, return -1. 🧩 How I Solved It: Used the Binary Search technique — repeatedly dividing the search space in half. Initialized two pointers, left and right, representing the current search range. Found the middle index mid, compared nums[mid] with target: If equal → returned mid. If smaller → shifted the left boundary rightward. If greater → moved the right boundary leftward. Continued until left > right, meaning the element isn’t found. ⚙️ Performance Stats: ⏱ Runtime: 0ms (⚡ beats 100%) 💾 Memory: 13.48MB (beats 31.70%) ✅ Testcases Passed: 47 / 47 ✨ Insight: Binary Search perfectly demonstrates divide-and-conquer at its best — turning linear scans into logarithmic efficiency 🚀 #LeetCode #Problem704 #BinarySearch #Algorithm #DSA #DivideAndConquer #Python #100DaysOfCode #CodingChallenge
To view or add a comment, sign in
-
-
🚀 𝗗𝗮𝘆 𝟲𝟭 𝗼𝗳 𝟯𝟲𝟱 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲! Today’s leetcode challenge: Count all palindromic substrings in a given string — every substring that reads the same forward and backward. 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: 647. Palindromic Substrings 🔗 𝐋𝐢𝐧𝐤: https://lnkd.in/gBJem2Pc ✔️ 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: - Each character can be the center of a palindrome. - For every index, expand outward while the substring remains a palindrome. - Handle both odd and even length palindromes separately by expanding around those centers. - Increment the count every time a palindrome is found. ⏱️ Time Complexity: O(n²) 📦 Space Complexity: O(1) 📝 Shared handwritten notes & code as well for deeper reference. This two-pass expand-around-center approach is clean, intuitive, and optimal for this problem! #LeetCode365 #Day61 #PalindromicSubstrings #StringAlgorithms #ExpandAroundCenter #ProblemSolving #CodingChallenge #Python #AI #ML #DL #AgenticAI
To view or add a comment, sign in
-
⚡ Understanding Quick Sort 🎯 Problem: Given an array of numbers, sort them in ascending order using the Quick Sort algorithm. 🧠 Concept: - Quick Sort is a powerful Divide & Conquer algorithm that sorts by selecting a pivot and placing it in its correct position. - Once the pivot settles, elements smaller than it move to the left, and larger ones move to the right — forming two sub-arrays that get sorted recursively. 🔹 Select a pivot (commonly the first, last, or a random element). 🔹 Move all smaller elements to the left of the pivot. 🔹 Move all larger elements to the right. 🔹 Recursively sort the left and right sub-arrays. 🔹 The array becomes fully sorted after all pivots settle into their correct spots. ⚙️ How the Partitioning Works: - Two pointers i (from the left) and j (from the right) move inward. - i moves until it finds an element greater than the pivot. - j moves until it finds an element smaller than the pivot. - If i < j, the elements are swapped. - Finally, the pivot is swapped into its correct position (j). - This makes j the partition index, and sorting continues around it. 🕒 Time Complexity: Average / Best: O(N log N) – Efficient due to effective partitioning. Worst: O(N²) – Happens when pivots are chosen poorly (like already sorted arrays without randomization). 💾 Space Complexity: O(1) – Only in-place swaps are used (excluding recursion stack). #Python #DSA #DsaStriver #LearnDaily #Share #ProblemSolving
To view or add a comment, sign in
-
-
🚀 DSA Challenge – Day 84 Problem: Reachable Nodes in a Restricted Tree 🌲🚫 This problem was a perfect blend of graph traversal and constraint handling, where we must carefully explore a tree while avoiding restricted nodes. 🧠 Problem Summary: You are given a tree with n nodes (0-indexed) and a list of edges that describe the connections between them. Some nodes are restricted, meaning you cannot visit or pass through them. Starting from node 0, the goal is to determine how many nodes are reachable without visiting any restricted ones. ⚙️ My Approach: 1️⃣ Build an adjacency list representation of the tree. 2️⃣ Store all restricted nodes in a set for quick lookup. 3️⃣ Use Depth-First Search (DFS) to traverse the graph, skipping restricted or already visited nodes. 4️⃣ Accumulate a count of all valid reachable nodes. 📈 Complexity: Time: O(n) → Each node and edge is processed once. Space: O(n) → For adjacency list, recursion stack, and visited set. ✨ Key Takeaway: Even simple DFS problems become interesting when constraints are introduced. Efficient use of sets and recursion can elegantly handle conditions like restricted traversal in trees or graphs. 🌿 🔖 #DSA #100DaysOfCode #LeetCode #GraphTheory #TreeTraversal #DFS #Python #ProblemSolving #CodingChallenge #InterviewPrep #Algorithms #EfficientCode #TechCommunity #CodeEveryday #LearningByBuilding
To view or add a comment, sign in
-
-
🚀 LeetCode #560: Subarray Sum Equals K — Cracked! This problem stands out as one of those that looks simple at first, but reveals an elegant pattern once you dive deeper. It beautifully combines logic, optimization, and mathematical thinking 💡 🧩 The Challenge Given an array of integers and a target value k, we need to find the number of continuous subarrays whose sum equals k. At first glance, a brute-force approach (checking all subarrays) might seem natural — but that quickly becomes inefficient as the array grows. ⚡ The Insight The key breakthrough comes from understanding prefix sums — the running total of elements as you move through the array. Instead of recalculating sums repeatedly, we track these prefix sums using a hashmap. Whenever the difference between the current prefix sum and k has appeared before, it means a subarray that sums to k exists. In one pass, we can find all such subarrays — turning a quadratic-time solution into a linear-time one 🔥 🧠 Why It’s Brilliant This approach teaches an important lesson: Many complex problems can be simplified by rethinking how we track and reuse information. It’s not always about doing more work — often, it’s about doing the right work. ⏱️ Complexity Time Complexity: O(n) Space Complexity: O(n) 💬 Takeaway This problem is a perfect example of how combining mathematical insight with data structures (like hashmaps) leads to elegant and efficient solutions. #LeetCode #DSA #Algorithms #ProblemSolving #Coding #Python #ComputerScience #LearningJourney #Tech
To view or add a comment, sign in
-
-
🧩 Understanding Merge Sort 🎯 Problem: Given an array of numbers, sort them in ascending order using the Merge Sort algorithm. 🧠 Concept: - Merge Sort follows the classic Divide & Conquer strategy. - Instead of sorting the entire array at once, it splits the array into smaller parts, sorts each part, and then merges them back together in sorted order. 🔹 Recursively divide the array into two halves. 🔹 Continue until each segment becomes a single element. 🔹 Merge the divided segments while sorting them on the way back up. 🔹 This merging step ensures the final output is fully sorted. ⚙️ How the Merge Step Works: In each merge operation: - Use two pointers — one for the left half and one for the right. - Pick the smaller element from both halves and build a temporary sorted list. - Copy the sorted elements back into the original array segment. - This ensures every merge produces a fully sorted section. 🕒 Time Complexity: O(N log N) – Because the array is divided recursively (log N) and each level requires merging N elements. Very consistent — performs the same even in worst cases. 💾 Space Complexity: O(N) – Extra space is needed to temporarily store the merged output. #DSA #Python #ProblemSolving #Sorting #LearnDaily #Share
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
Halfway there and still going, that's the spirit 🔥💯