Maximum Stack - Microsoft Top Interview Questions


Problem Statement :


Implement a maximum stack with the following methods:

MaximumStack() constructs a new instance of a maximum stack

append(int val) appends val to the stack

peek() retrieves the last element in the stack
max() retrieves the maximum value in the stack

pop() pops and returns the last element in the stack

popmax() pops and returns the last occurrence of the maximum value in the stack

You can assume that for peek, max, pop and popmax, the stack is non-empty when they are called.



Constraints



n ≤ 100,000 where n is the number of methods that will be called.

Example 1

Input

methods = ["constructor", "append", "append", "append", "peek", "max", "popmax", "max", "pop", "peek"]

arguments = [[], [1], [3], [2], [], [], [], [], [], []]`

Output

[None, None, None, None, 2, 3, 3, 2, 2, 1]

Explanation

We create a MaximumStack

Append 1 to the stack

Append 3 to the stack

Append 2 to the stack

Peek the top element which is 2

Max value of the stack so far is max(1, 3, 2) == 3

We pop the max value of 3

Max value of the stack is now max(1, 2) == 2

We pop the top element which is 2

Peek the top element which is now 1



Solution :



title-img




                        Solution in C++ :

class MaximumStack {
    public:
    int idx = 0;
    set<pair<int, int>> s;
    vector<pair<int, int>> v;

    void append(int val) {
        v.emplace_back(val, ++idx);
        s.emplace(val, idx);
    }

    int peek() {
        while (s.find(v.back()) == s.end()) v.pop_back();
        return v.back().first;
    }

    int max() {
        return s.rbegin()->first;
    }

    int pop() {
        while (s.find(v.back()) == s.end()) v.pop_back();
        auto [x, y] = v.back();
        v.pop_back();
        s.erase(s.find({x, y}));
        return x;
    }

    int popmax() {
        auto [x, y] = *s.rbegin();
        s.erase(prev(s.end()));
        return x;
    }
};
                    


                        Solution in Java :

class MaximumStack {
    public:
    map<int, vector<list<int>::iterator>> m1;
    list<int> L;
    MaximumStack() {
    }
    void append(int val) {
        L.push_back(val);
        m1[val].push_back(prev(L.end()));
    }

    int peek() {
        return *prev(L.end());
    }
    int max() {
        return m1.rbegin()->first;
    }
    int pop() {
        int val = peek();
        erase(val);
        return val;
    }
    void erase(int val) {
        vector<list<int>::iterator> &v = m1[val];
        auto it = v.back();
        v.pop_back();
        if (v.size() == 0) m1.erase(val);
        L.erase(it);
    }
    int popmax() {
        int val = m1.rbegin()->first;
        erase(val);
        return val;
    }
};
                    


                        Solution in Python : 
                            
class MaximumStack:
    def __init__(self):
        # `time` is increased when an element is appended. So each `time`
        # corresponds to a unique element, as recorded in `time_to_val`.
        # When an element has been popped, its corresponding time, thus
        # becoming invalid, will be deleted from `time_to_val`.
        self.time = 0
        self.time_to_val = {}

        # a LIFO stack of uniq pairs `(element, time)`
        self.stk = []

        # a priority queue of uniq pairs `(-element, -time)` for max-related stuff
        self.pq = []

    def append(self, val):
        self.time += 1
        self.time_to_val[self.time] = val
        self.stk.append((val, self.time))
        heapq.heappush(self.pq, (-val, -self.time))

    # After this operation, the top elements of `stk` and `pq` are valid.
    def _pop_invalid_times(self, invalid_time):
        del self.time_to_val[invalid_time]
        while self.stk and (self.stk[-1][1] not in self.time_to_val):
            self.stk.pop()
        while self.pq and (-self.pq[0][1] not in self.time_to_val):
            heapq.heappop(self.pq)

    def peek(self):
        return self.stk[-1][0]

    def max(self):
        return -self.pq[0][0]

    def pop(self):
        entry = self.stk.pop()
        self._pop_invalid_times(entry[1])
        return entry[0]

    def popmax(self):
        entry = heapq.heappop(self.pq)
        self._pop_invalid_times(-entry[1])
        return -entry[0]
                    


View More Similar Problems

Simple Text Editor

In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,

View Solution →

Poisonous Plants

There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan

View Solution →

AND xor OR

Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value

View Solution →

Waiter

You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in from top to bottom in answers. In the next iteration, do the

View Solution →

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →