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

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →