LeetCode Problem 155 "Min Stack": Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function. Approach: we can implement a single stack and store values as tuples (current element, min so far). But wait ... consider edge case when we pop and the stack becomes empty, so to handle this we consider two conditions- one when stack becomes empty, we set min so far to +ve infinity again, second whenever we pop elements, if stack is not empty, we update min so far to the top of the stack's min so far. In this way we can keep track of the minimum element upto a specific stack level. Time complexity of all the operations: O(1) #Python #LeetCode #ProblemSolving #DSA #InterviewPrep #DataStructures #Algorithms #Programming
Min Stack Design with O(1) Time Complexity
More Relevant Posts
-
🚀 Another LeetCode Problem Solved: Palindrome Number! 🔗 Check out my solution: https://lnkd.in/dwDMqXXn 💡 Problem Overview Given an integer x, determine whether it is a palindrome — meaning it reads the same forward and backward. (LeetCode) Examples: ✔ 121 → Palindrome ❌ -121 → Not a palindrome ❌ 10 → Not a palindrome 🧠 My Approach (Digit Reversal) Instead of converting the number to a string, I used a mathematical approach: Extract digits using % 10 Reverse the number step by step Compare reversed number with original ⚙️ Key Learnings ✔ Strong understanding of number manipulation ✔ Importance of handling edge cases (negative numbers, trailing zeros) (leet-solution.com) ✔ Practicing clean and efficient logic ⏱️ Complexity • Time Complexity: O(log n) • Space Complexity: O(1) 🔥 Why this problem matters Even though it’s an “easy” problem, it builds: Logical thinking Problem-solving fundamentals Confidence for bigger challenges #LeetCode #DSA #Python #CodingJourney #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
Day 10/100 – DSA Challenge Today’s problem: Move Zeroes (LeetCode 283) What I Learned: The goal was to move all zeroes to the end of an array while maintaining the relative order of non-zero elements — and importantly, doing it in-place. Key Idea: Two-Pointer Technique I used a two-pointer approach: One pointer (fast) iterates through the array Another pointer (slow) tracks where the next non-zero element should go Whenever a non-zero element is found, it is swapped with the element at the slow pointer, ensuring all non-zero elements are shifted forward while zeroes naturally move to the end. Why this approach? Maintains order of elements Works in O(n) time complexity Uses O(1) extra space (in-place) Takeaway: This problem reinforced how powerful the two-pointer technique is for array manipulation problems, especially when constraints require in-place operations. Looking forward to tackling more problems and improving consistency! #Day10 #100DaysOfCode #DSA #Python #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
-
𝗜𝘁 𝘀𝘁𝗮𝗿𝘁𝘀 𝘄𝗶𝘁𝗵 𝗮 𝗻𝗼𝗯𝗹𝗲 𝗶𝗻𝘁𝗲𝗻𝘁𝗶𝗼𝗻: "𝗜 𝗮𝗺 𝗴𝗼𝗶𝗻𝗴 𝘁𝗼 𝘀𝗮𝘃𝗲 𝘁𝗶𝗺𝗲." It ends with you debugging a Python script at 2 AM for a process that you could have finished by hand before lunch. Engineers love to solve problems with code. But sometimes, code is the most expensive solution. Here is the math on why "𝗔𝘂𝘁𝗼𝗺𝗮𝘁𝗶𝗻𝗴 𝗘𝘃𝗲𝗿𝘆𝘁𝗵𝗶𝗻𝗴" is actually hurting your productivity. 𝗥𝗲𝗴𝗶𝘀𝘁𝗲𝗿 𝗻𝗼𝘄 : https://lnkd.in/dkVrmCHc #DeveloperLife #Automation #Productivity #IndieHacker #Engineering #TheVentureBuild
To view or add a comment, sign in
-
Building this trading bot taught me how powerful clean architecture, modular design, and API‑driven automation can be. My goal wasn’t to create a complex system — but a simple, reliable, and transparent bot that anyone can understand. This project helped me sharpen my Python fundamentals, improve my debugging discipline, and design a structure that scales. Excited to keep improving it with strategies, risk checks, and backtesting. - Drafted with the help from Copilot. #Python #TradingBot #AlgorithmicTrading #PythonProjects #Automation #APIDevelopment #CodingJourney #LearningInPublic GIT hub link for code: https://lnkd.in/d_cCwG-r
To view or add a comment, sign in
-
Code that writes code. 🌌 There is a point in every developer's journey where you stop thinking about Logic and start thinking about Patterns. Advanced Python is about: ~Abstraction: Using Protocols and Generics for structural typing. ~Automation: Using advanced Decorators to inject behavior across entire systems. ~Reliability: Understanding the memory manager so you can prevent leaks before they start. We use these "hidden" features not to make the code more complex, but to make the usage of our code more simple for everyone else. Which part of the "Advanced Mindset" was the hardest for you to learn? For me, it was finally mastering asyncio flow control. #CleanCode #Pythonic #ProgrammingPrinciples #SystemDesign #AdvancedCoding
To view or add a comment, sign in
-
-
C Gains Market Share as Rust Growth Stabilizes in TIOBE Index April 2026 📌 C surges to second place in the April 2026 TIOBE Index, outpacing Rust’s stalled growth - a shift signaling rising demand for low-level systems work. While Python holds top spot, Rust’s momentum slows despite performance wins, hinting that technical prowess alone isn’t enough for mainstream adoption. Devs and engineers now face a tighter race between high-level automation and raw system control. 🔗 Read more: https://lnkd.in/d9_74i_e #Python #Rust #Tiobeindex #Programminglanguages
To view or add a comment, sign in
-
🚀 Solved today’s LeetCode challenge: Longest Common Prefix 💻🔥 Problem: Given an array of strings, find the longest common starting substring among all strings. ✅ Example: ["flower", "flow", "flight"] → "fl" ["dog", "racecar", "car"] → "" 🧠 My Approach: Started with the first word as a prefix and compared it with the remaining strings one by one. Whenever a mismatch happened, I kept shrinking the prefix from the end until it matched. This helped me understand: 🔹 String slicing in Python 🔹 Prefix matching logic 🔹 Edge case handling 🔹 Writing optimized clean code 💡 Time Complexity: O(n * m) (n = number of strings, m = prefix length) Consistency > Motivation. One problem every day builds strong problem-solving skills 📈 Check Out : https://lnkd.in/dtumdVUQ #LeetCode #Python #DSA #CodingJourney #ProblemSolving #100DaysOfCode #SoftwareEngineer #Programming #Tech #Learning
To view or add a comment, sign in
-
Min Stack: Parallel Stack Tracks Running Minimum in O(1) Finding minimum naively requires O(n) scan. Solution: maintain parallel stack where each position stores minimum of all elements at/below it. Push/pop synchronize both stacks. getMin becomes O(1) lookup of minStack top. Auxiliary Stack Pattern: For O(1) access to aggregate property (min, max, sum) at any depth, maintain parallel stack tracking that property. Space doubles but all operations stay O(1). Time: O(1) all ops | Space: O(n) #Stack #AuxiliaryStructure #MinTracking #ConstantTime #Python #DataStructureDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🗓 7 April 2026 🚀 LeetCode #703 – Kth Largest Element in a Stream Solved this problem using a clean and efficient Min Heap approach 🔥 💡 Instead of storing all elements, I maintained only the top K largest elements, which makes the solution scalable for large data streams. 🧠 Approach: • Created a min heap • Added elements in the constructor • If size exceeds k → removed the smallest element • In add(): – Push new value into heap – Pop if size exceeds k – Return the top element (Kth ) ⚡ Time Complexity: O(n log k) 📦 Space Complexity: O(k) 💭 Key Insight: We don’t need to store all elements — just maintain the top k elements. The smallest among them is the answer 🎯 #LeetCode #DSA #Python #Coding #100DaysOfCode #Heap
To view or add a comment, sign in
-
-
💡 Cracking the Maximum Product Subarray Problem (Without Overcomplicating It) Today I worked on a classic DSA problem: Maximum Product Subarray — and found a simple yet powerful approach worth sharing. Most solutions focus on tracking max/min dynamically. But there’s a cleaner trick: 👉 Traverse the array from both directions (prefix & suffix) Why this works: Negative numbers can flip the product sign A single left-to-right pass might miss the optimal answer Scanning from both ends ensures we capture every possibility 🔁 Key Idea: Maintain two running products: Prefix (left → right) Suffix (right → left) Reset when product becomes 0 Track the maximum throughout ⚡ Complexity: Time: O(n) Space: O(1) Python code : https://lnkd.in/gZtCw9_i What I liked about this approach is its simplicity and elegance — no extra arrays, no complex state tracking. Sometimes, the best solutions aren’t the most complicated ones — just the most thoughtful. Have you tried solving this problem using a different approach? Would love to hear your thoughts 👇 #DataStructures #Algorithms #CodingInterview #Python #LeetCode #ProblemSolving Rajan Arora
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