Stack Of Plates

  • 0

    Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure SetOfStacks that mimics this. SetOfStacks should be composed of several stacks, and should create a new stack once the previous one exceeds capacity. SetOfStacks.push() and SetOfStacks.pop() should behave identically to a single stack (that is, pop() should return the same values as it would if there were just a single stack).

    Input: capacity = 4 , push(1),push(2),push(2),pop,push(3),push(4),push(5)

    Output: [[1,2,3,4],[5]]

  • 0
    class SetOfStacks {
    	ArrayList<Stack> sets = new ArrayList<Stack>();
    	int counter = 0, capacity = 4;
    	Stack<Integer> stack;
    	void push(int i) {
    		if (counter == capacity || counter == 0) {
    			counter = 0;
    			stack = new Stack<>();
    	int pop() {
    		if(counter == 1)
    			counter = capacity;
    		return (Integer) sets.get(sets.size() - 1).pop();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.