Implement Stack using Arrays

Pattern: Implementation

easy

Keep an array and a size. The top is data[size - 1]. Push writes at data[size]; pop reads data[size - 1] and shrinks size. When the array is full, copy it into one twice as big, so pushes stay O(1) on average.

The problem

Build a class ArrayStack with push(x), pop() (remove and return the top), top() (return it without removing) and isEmpty(), storing the items in an array. For example, after push(5), push(10): top() is 10, pop() is 10, isEmpty() is false.

On an empty structure, pop, top and peek return -1. This is this guide's own rule; the linked page does not say what happens.

Think first

  • Where is the top of the stack in the array?
  • What must change on a push, and on a pop?
  • What should happen when the array is full?

Hints

    Brute force, and why it fails

    Using the front of the array as the top means shifting every item on each push and pop: O(n) per operation.

    The key insight

    Putting the top at the end of the used part means push and pop touch one slot. Doubling when full makes the rare copy cost O(1) per push on average.

    Dry run

    0 
    1 
    2 
    3 
    size0

    Start with an array of capacity 4 and size 0.

    Step 1 of 5

    The plan

    push(x):  if size == capacity: data = copy of data with twice the length
              data[size] = x; size += 1
    pop():    if size == 0: return -1
              size -= 1; return data[size]
    top():    return -1 if size == 0 else data[size - 1]
    isEmpty(): return size == 0
    

    Complexity

    Time
    O(1) per operation (amortised for push)
    Space
    O(n)

    Each operation touches one slot. A doubling copy of n items happens only after n pushes, so it adds O(1) to each on average.

    Edge cases

    • Pop or top on an empty stack: -1.
    • Many pushes in a row: the array grows several times.
    • Negative values are fine; -1 as a value and as the empty signal look alike, which is why real code throws instead.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class ArrayStack {
        private int[] data = new int[4];
        private int size = 0;                       // the top is data[size - 1]
    
        public void push(int x) {
            if (size == data.length) data = Arrays.copyOf(data, size * 2);   // full: double the array
            data[size++] = x;
        }
    
        public int pop() {
            if (size == 0) return -1;               // this guide's rule for an empty stack
            return data[--size];
        }
    
        public int top() {
            return size == 0 ? -1 : data[size - 1];
        }
    
        public boolean isEmpty() {
            return size == 0;
        }
    }

    C++

    class ArrayStack {
    public:
        vector<int> data = vector<int>(4);
        int size = 0;                               // the top is data[size - 1]
    
        void push(int x) {
            if (size == static_cast<int>(data.size())) data.resize(size * 2);   // full: double the array
            data[size++] = x;
        }
    
        int pop() {
            if (size == 0) return -1;               // this guide's rule for an empty stack
            return data[--size];
        }
    
        int top() {
            return size == 0 ? -1 : data[size - 1];
        }
    
        bool isEmpty() {
            return size == 0;
        }
    };

    Python

    class ArrayStack:
        def __init__(self):
            self.data = [0] * 4
            self.size = 0                           # the top is data[size - 1]
    
        def push(self, x: int) -> None:
            if self.size == len(self.data):
                self.data.extend([0] * len(self.data))   # full: double the array
            self.data[self.size] = x
            self.size += 1
    
        def pop(self) -> int:
            if self.size == 0:
                return -1                           # this guide's rule for an empty stack
            self.size -= 1
            return self.data[self.size]
    
        def top(self) -> int:
            return -1 if self.size == 0 else self.data[self.size - 1]
    
        def isEmpty(self) -> bool:
            return self.size == 0

    Common mistakes

    • Reading data[size] instead of data[size - 1] for the top.
    • Decreasing size after reading, in the wrong order, and returning the wrong slot.
    • Forgetting the empty check.

    Similar problems