close

DEV Community

Jaspreet singh
Jaspreet singh

Posted on

Implement stack using array

Problem Statement

Implement a Stack using an array supporting:

push(x)
pop()
peek()
isEmpty()
isFull()
Enter fullscreen mode Exit fullscreen mode

Following LIFO:

Last In First Out
Enter fullscreen mode Exit fullscreen mode

Brute Force Intuition

Use a dynamic structure like:

ArrayList<Integer>
Enter fullscreen mode Exit fullscreen mode

Push:

add()
Enter fullscreen mode Exit fullscreen mode

Pop:

remove(size-1)
Enter fullscreen mode Exit fullscreen mode

This works but doesn't teach how Stack works internally.


Moving Towards the Optimal Approach

A Stack only needs:

Array
+
Top Pointer
Enter fullscreen mode Exit fullscreen mode

Maintain:

top = -1
Enter fullscreen mode Exit fullscreen mode

Whenever we push:

arr[++top] = x;
Enter fullscreen mode Exit fullscreen mode

Whenever we pop:

top--;
Enter fullscreen mode Exit fullscreen mode

Pattern Recognition

Stack

=> Array + Top Index
Enter fullscreen mode Exit fullscreen mode

Optimal Java Solution

class myStack {

    int[] arr;
    int top;

    public myStack(int n) {

        arr = new int[n];
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == arr.length - 1;
    }

    public void push(int x) {

        if (!isFull()) {
            arr[++top] = x;
        }
    }

    public void pop() {

        if (!isEmpty()) {
            top--;
        }
    }

    public int peek() {

        if (!isEmpty()) {
            return arr[top];
        }

        return -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Dry Run

push(10)

push(20)

push(30)
Enter fullscreen mode Exit fullscreen mode

Stack:

30 ← top
20
10
Enter fullscreen mode Exit fullscreen mode
pop()
Enter fullscreen mode Exit fullscreen mode

Stack:

20 ← top
10
Enter fullscreen mode Exit fullscreen mode
peek()
Enter fullscreen mode Exit fullscreen mode

Returns:

20
Enter fullscreen mode Exit fullscreen mode

Complexity Analysis

Operation Complexity
Push O(1)
Pop O(1)
Peek O(1)

Interview One-Liner

Maintain a top pointer and perform all operations directly on the array.

Top comments (0)