Solved Kth Smallest Element in a BST today Used an iterative inorder traversal (DFS with stack) to efficiently find the answer without extra space for storing nodes. Key idea: 👉 Inorder traversal of a BST gives nodes in sorted order 👉 So the k-th visited node is the answer Instead of recursion, I used a stack to simulate traversal: Go left as much as possible Process node Move right Clean, efficient, and interview-friendly ✅ Time: O(H + k) Space: O(H) (stack) Consistent practice is making these patterns feel natural 🚀 #LeetCode #DataStructures #Algorithms #Python #CodingInterview
Junaid Arshad’s Post
More Relevant Posts
-
🗓 7 April 2026 LeetCode Problem #128 – Longest Consecutive Sequence Solved the problem of finding the longest consecutive sequence in an unsorted array. Key insight: use a set for O(1) lookups and only start counting sequences from numbers that are the beginning of a sequence. Takeaways: - Using the right data structure reduces time complexity from O(n²) to O(n). - Avoid redundant work while scanning arrays. - Handle edge cases like empty or single-element arrays efficiently. This problem reinforces how a smart approach beats brute force every time! #LeetCode #Algorithms #Python #DataStructures #ProblemSolving #Coding #TechLearning
To view or add a comment, sign in
-
-
Day 32/100 – Diameter of Binary Tree Today’s problem looked simple on the surface, but it really tested my understanding of tree traversal and recursion. Key Insight: The diameter of a binary tree isn’t about paths from root—it’s about the longest path between any two nodes. The trick? At every node, calculate: Left subtree height Right subtree height Update diameter = left + right This turns a potentially complex problem into a smooth DFS + height calculation. What I learned: How to combine recursion with global state Thinking beyond root-based solutions Every node can be the "center" of the longest path Time Complexity: O(n) Space Complexity: O(h) Consistency > intensity. On to Day 33 #100DaysOfCode #DataStructures #Algorithms #LeetCode #Python #CodingJourney
To view or add a comment, sign in
-
-
🚀 Cracked “Minimum Distance to Target” with a clean and efficient approach! My thought process was simple and structured: ➡️ First, I iterated through the array to identify all indices where the target element appears. ➡️ For each match, I calculated the absolute distance from the given start index. ➡️ Stored these distances and finally returned the minimum among them. 💡 This approach keeps things intuitive and avoids overcomplication—focus on correctness first, then optimize if needed. ✅ Time Complexity: O(n) ✅ Space Complexity: O(n) (can be optimized further by tracking min on the go) Sometimes the simplest logic gives the best results 🔥 #LeetCode #ProblemSolving #DataStructures #Algorithms #Python #CodingJourney #TechGrowth #Consistency #LearnInPublic #WomenInTech #100DaysOfCode #CodingLife #SoftwareEngineering #PlacementPrep
To view or add a comment, sign in
-
-
Binary Tree Level Order Traversal: Queue with Level Isolation BFS naturally traverses level-by-level. Key technique: snapshot queue length before processing current level. Process exactly that many nodes, collecting values into level list while enqueueing children for next iteration. This prevents mixing levels. Level Isolation: Pre-loop length snapshot prevents newly-added children from affecting current level's iteration count. This pattern enables clean level-by-level processing. Time: O(n) | Space: O(w) where w = max width #BFS #LevelOrderTraversal #QueuePattern #TreeAlgorithms #Python #AlgorithmDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Kth Smallest in BST: Iterative Inorder with Early Termination Inorder traversal of BST yields sorted order. Instead of building full sorted list, use iterative inorder with counter — return at kth visit. Early termination avoids processing entire tree when k is small. Early Exit Advantage: Iterative inorder with counter stops at k, avoiding O(n) space for full list. Best when k << n. Stack simulates recursion while enabling early termination. Time: O(h + k) | Space: O(h) #BST #InorderTraversal #EarlyTermination #IterativeSearch #Python #AlgorithmDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 LeetCode Grind: Find First and Last Position of Element in Sorted Array Just solved a classic searching problem! 💻 Problem: Given a sorted array, find the starting and ending position of a given target value. The Challenge: Achieving $O(\log n)$ runtime complexity. Key Takeaway: While a linear scan works, leveraging Binary Search twice (once for the left boundary and once for the right) is the key to meeting the performance constraints. It’s a great reminder of how powerful binary search is for optimizing search operations on sorted data. Checking off another one as I continue to sharpen my problem-solving skills! 🛠️ #LeetCode #CodingChallenge #Python #Algorithms #DataStructures #ProblemSolving #TechJourney #BinarySearch
To view or add a comment, sign in
-
-
Tree Diameter: Tracking Height and Max Path with Global State Longest path might not include current node, so can't compose answer from return values alone. Solution: return height for parent's calculation, track diameter globally. At each node, potential diameter through it = left_height + right_height. Dual-Purpose Recursion: When local computation differs from parent's need, split concerns — return for upward propagation, global state for aggregation. Pattern appears in weighted paths, subtree properties. Time: O(n) | Space: O(h) #TreeAlgorithms #GlobalState #DiameterProblem #DualPurposeRecursion #Python #AlgorithmDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
Search Rotated Sorted Array: Binary Search with Sorted Half Detection Rotation disrupts global order but one half stays sorted always. Determine which half is sorted by comparing mid with endpoints. If target falls within sorted half's range, search there; otherwise search rotated half. Preserves O(log n). Partial Invariant: When global invariant breaks, find preserved local properties. One half maintains sorting despite rotation — exploit this for logarithmic search. Time: O(log n) | Space: O(1) #BinarySearch #RotatedArray #PartialInvariant #SearchOptimization #Python #AlgorithmDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 Day 9 of #30DaysOfDSA Revisited the problem: Longest Palindromic Substring 🔍 💡 DSA Pattern Focus: 👉 Palindrome Pattern + Expand Around Center (Two Pointer Technique) 🧠 What I focused on today: Instead of just solving, I worked on understanding the intuition deeply. Why expanding from center works efficiently Difference between odd & even length palindromes How this approach avoids unnecessary substring checks ⚡ Compared to brute force (O(n³)), this optimized solution runs in O(n²) time and O(1) space. 📌 Key Takeaways: Same problem can teach multiple layers of understanding Depth > Number of questions solved Strong fundamentals make complex problems easier 🔥 Improving not just by solving problems, but by understanding them better each day. #DSA #LeetCode #ProblemSolving #CodingJourney #Consistency #Python #SoftwareEngineering
To view or add a comment, sign in
-
-
Top K Frequent: Bucket Sort Beats Heap with O(n) Time Heap solution costs O(n log k). Bucket sort achieves O(n) by exploiting constraint — frequencies ≤ array length. Index represents frequency, value is list of elements with that frequency. Traverse high-to-low, collecting k elements. Bucket Sort Advantage: When value range is bounded (frequencies ≤ n), bucket sort beats comparison-based sorting. Exploiting constraints transforms complexity. Time: O(n) | Space: O(n) #BucketSort #TopK #FrequencyAnalysis #ComplexityReduction #Python #AlgorithmOptimization #SoftwareEngineering
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