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

Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

View Solution →

Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

View Solution →

Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

View Solution →

Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy

View Solution →

Heavy Light 2 White Falcon

White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr

View Solution →

Library Query

A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra

View Solution →