Incrementable Stack - Microsoft Top Interview Questions


Problem Statement :


Implement a stack with the following methods:

IncrementableStack() constructs a new instance of an incrementable stack

append(int val) appends val to the stack

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

increment(int inc, inc count) increments the value of bottom count elements by inc

Each method should be done in \mathcal{O}(1)O(1) time. You can assume that for pop, the stack is 
non-empty when it is called.



Constraints



n ≤ 100,000 where n is the number of calls to append, pop, and increment`.

Example 1

Input

methods = ["constructor", "append", "append", "increment", "pop", "pop"]

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

Output

[None, None, None, None, 2, 6]



Solution :



title-img




                        Solution in C++ :

class IncrementableStack {
    public:
    // {value, increment}
    // all the elements below this element will get affected by the increment value
    vector<pair<int, int>> s;
    IncrementableStack() {
    }

    void append(int val) {
        s.push_back({val, 0});
    }

    int pop() {
        int val = s.back().first;
        int inc = s.back().second;
        int ret = val + inc;
        if (s.size() > 1) s[s.size() - 2].second += inc;
        s.pop_back();
        return ret;
    }

    void increment(int inc, int count) {
        if (s.size() && count) {
            int index = min(count - 1, (int)s.size() - 1);
            s[index].second += inc;
        }
    }
};
                    


                        Solution in Java :

import java.util.*;

class IncrementableStack {
    // first num is val, second is increment
    LinkedList<int[]> stack = new LinkedList<>();

    public void append(int val) {
        stack.add(new int[] {val, 0});
    }

    public int pop() {
        // Get top of stack
        int[] pair = stack.getLast();
        int val = pair[0], incr = pair[1];

        // Update next pair in stack
        int len = stack.size();
        if (len > 1) {
            stack.get(len - 2)[1] += incr;
        }

        // Remove top of stack
        stack.removeLast();

        return val + incr;
    }

    public void increment(int inc, int count) {
        // Increase increment of desired position count
        if (!stack.isEmpty() && count > 0) {
            int index = Math.min(stack.size() - 1, count - 1);
            stack.get(index)[1] += inc;
        }
    }
}
                    


                        Solution in Python : 
                            
class IncrementableStack:
    def __init__(self):
        self.stack = []
        self.incs = []

    def append(self, val):
        self.stack.append(val)
        self.incs.append(0)

    def pop(self):
        inc = self.incs.pop()
        if self.incs:
            self.incs[-1] += inc
        return self.stack.pop() + inc

    def increment(self, inc, count):
        if self.incs and count > 0:
            if count <= len(self.incs):
                self.incs[count - 1] += inc
            else:
                self.incs[-1] += inc
                    


View More Similar Problems

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →