Skip to content
Minsing Log
Go back

English Edition

Stack -> Finding the Minimum Value

Programming & CS

Intuition

Sol 1. Two arrays

  1. 2 arrays
  1. Implement the stack as is
  2. Whenever min_stack is updated, repeatedly assign the minimum value to each index

a stack is implemented by using an Int index called top as a cursor

Sol 2. Mathematical trick with one array

Odd-numbered indexes are stack Even-numbered indexes are min_stack

Sol 2. Mathematical trick with one array 2 -> still 70%

// all operations in O(1) time and O(1) extra space.

#include <iostream>
#include <stack>
using namespace std;

// A user defined stack that supports getMin() in
// addition to push(), pop() and peek()
class SpecialStack {
  private:
    stack<int> s;
    int minEle;
    
  public:
    SpecialStack() {
        minEle = -1;
    }
    
    // Add an element to the top of Stack
    void push(int x) {
        if (s.empty()) {
            minEle = x;
            s.push(x);
        }

        // If new number is less than minEle
        else if (x < minEle) {
            s.push(2 * x - minEle);
            minEle = x;
        }

        else {
            s.push(x);
        }
    }
    
    // Remove the top element from the Stack
    void pop() {
        if (s.empty()) {
            return ;
        }
        
        int top = s.top();
        s.pop();
        
        // Minimum will change, if the minimum element
        // of the stack is being removed.
        if (top < minEle) {
            minEle = 2 * minEle - top;
        }
    }
    
    // Returns top element of the Stack
    int peek() {
        if (s.empty()) {
            return -1;
        }

        int top = s.top();

        // If minEle > top means minEle stores value of top.
        return (minEle > top) ? minEle : top;
    }
    
    // Finds minimum element of Stack
    int getMin() {
        if (s.empty())
            return -1;

        // variable minEle stores the minimum element
        // in the stack.
        return minEle;
    }
};

int main() {
    SpecialStack ss;
    
    // Function calls
    ss.push(2);
    ss.push(3);
    cout << ss.peek() << " ";
    ss.pop();
    cout << ss.getMin() << " ";
    ss.push(1);
    cout << ss.getMin() << " ";
}

Why push works

How 2*x – minEle is less than x in push()? 


x < minEle which means x – minEle < 0 


// Adding x on both sides
x – minEle + x < 0 + x 
2*x – minEle < x 
We can conclude 2*x – minEle < new minEle 

Why pop is restored

How previous minimum element, prevMinEle is, 2*minEle – y
in pop() is y the popped element?


 // We pushed y as 2x – prevMinEle. Here 
// prevMinEle is minEle before y was inserted


y = 2*x – prevMinEle  


// Value of minEle was made equal to x
minEle = x 


new minEle = 2 * minEle – y 
                   = 2*x – (2*x – prevMinEle)
                   = prevMinEle // This is what we wanted

https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/

Sol 3. Linked list

Sol4. Using the standard stack

공개 여정 구독

글이 올라오면 이메일로 보내드릴게요.

개발, 창업, 배움, 실패와 회고를 짧고 솔직하게 기록합니다. 검색으로 스쳐가는 독자가 아니라 여정을 따라오는 팬을 만들기 위한 뉴스레터입니다.

뉴스레터는 준비 중입니다. 그동안 RSS 로 구독하거나 이메일 로 알림을 요청해 주세요.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
How to Map a Func to Elements of Multiple Nested Data Structures
Next Post
Interpretation of Bayes' Theorem