# Design a Stack With Increment Operation in C++

Suppose we want to design a stack that supports the following operations.

• CustomStack(int maxSize) This initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.

• void push(int x) This inserts x to the top of the stack if the stack hasn't reached the maxSize.

• int pop() This deletes and returns the top of stack or -1 if the stack is empty.

• void inc(int k, int val) This increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.

To solve this, we will follow these steps −

• Define two arrays st and inc, and create one integer type data cap

• in the initializer, set cap := N and set inc := a new array of size N + 10

• For the push(x) method, if size of stack is not cap, then insert x into st.

• The pop() operation will be like −

• if st is empty, then return -1

• otherwise

• top of stack := top of stack + inc[top index of stack]

• if stack has some element, then increase inc[size of st - 2] by inc[size of st – 1]

• inc[size of s - 1] := 0

• x := last element of st

• return x

• The inc() method will work as follows −

• decrease k by 1

• k := min of k and size of st – 1

• if k < 0, then return

• increase inc[k] by val.

## Example (C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class CustomStack {
public:
vector <int> st;
vector <int> inc;
int cap;
CustomStack(int N) {
cap = N;
inc = vector <int>(N + 10);
}
void push(int x) {
if(st.size() == cap) return;
st.push_back(x);
}
int pop() {
if(st.empty()) return -1;
else{
st.back() += inc[st.size() - 1];
if(st.size() - 1 > 0 ){
inc[st.size() - 2] += inc[st.size() - 1];
}
inc[st.size() - 1] = 0;
int x = st.back();
st.pop_back();
return x;
}
}
void increment(int k, int val) {
k--;
k = min(k, (int)st.size() - 1);
if(k < 0) return;
inc[k] += val;
}
};
main(){
CustomStack ob(3);
ob.push(1);
ob.push(2);
cout << ob.pop() << endl;
ob.push(2);
ob.push(3);
ob.push(4);
ob.increment(5, 100);
ob.increment(2, 100);
cout << ob.pop() << endl;
cout << ob.pop() << endl;
cout << ob.pop() << endl;
cout << ob.pop() << endl;
}

## Input

See the main() in the program

## Output

2
103
202
201
-1

Advertisements