GeeksforGeeks Easy

Implement Stack using Arrays

Implement Stack using Arrays is a GFG problem (Easy). Build a class myStack(n) whose storage is an array of size n, with five methods:

  • push(x) puts x on top; pop() removes the top element.
  • peek() returns the top element, or −1 if the stack is empty.
  • isEmpty() and isFull() say whether the stack holds 0 or n elements.

A pop or peek can arrive while the stack is empty, so those calls must leave it unharmed.

Constraints
  • 1 <= n <= 10³ (array size)
  • 1 <= number of queries <= 10³
  • 0 <= x <= 10⁵
stackdesign
Open on GeeksforGeeks ↗
02

Intuition

A stack only ever works at one end. Put that end at the back of the array, where adding or removing an element never moves any other element. Then the whole state of the stack is one integer, top: the index of the newest element, or −1 when there is none.

  • Push and pop move top up or down by one slot.
  • Pop erases nothing. A value above top is invisible to every method, and the next push writes over it.
How to spot this pattern

"Build a stack on a fixed-size array" means one moving index at the back of the array. Every method is a bounds check on that index plus at most one array read or write.

03

Approach

Try it first

Before reading on, decide what top should hold before the first push, and write push so the first element lands on index 0 without a special case.

1

Start with n slots and top at −1

Allocate the array once and set top = -1. With −1 as the empty value, the first push lands on index 0 using the same two lines as every other push, and top + 1 is always the number of stored elements.

2

Push: check for room, move top up, then write

If isFull() is true, return without doing anything. Otherwise add 1 to top and write x at arr[top]. The order matters because top points at the last used slot, not at the next free one.

3

Pop: check for an element, then move top down

If isEmpty() is true, return. Otherwise subtract 1 from top. The check keeps top from dropping below −1, which would make the next push write to the wrong slot.

4

Answer peek, isEmpty and isFull from top

peek() returns arr[top], or −1 when the stack is empty. isEmpty() is top == -1 and isFull() is top == n - 1. None of them loops, so every method takes the same small amount of time however full the stack is.

04

Code in Python, C++ and Java

▶1class myStack:
▶2 def __init__(self, n):
▶3 self.arr = [0] * n
▶4 self.top = -1
▶5 
▶6 def isEmpty(self):
▶7 return self.top == -1
▶8 
▶9 def isFull(self):
▶10 return self.top == len(self.arr) - 1
▶11 
▶12 def push(self, x):
▶13 if self.isFull():
▶14 return
▶15 self.top += 1
▶16 self.arr[self.top] = x
▶17 
▶18 def pop(self):
▶19 if self.isEmpty():
▶20 return
▶21 self.top -= 1
▶22 
▶23 def peek(self):
▶24 if self.isEmpty():
▶25 return -1
▶26 return self.arr[self.top]
call−1empty012topreturnedempty stack: 3 slots, top below slot 0
n3
top−1
The array has 3 slots and nothing in them. top starts at −1, one below index 0, so the first push will land on index 0 with no special case.
callpush 5−1empty0512topreturnedpush 5: top moves up to slot 0, write 5
callpush 5
top0
There is room, so top moves up first, from −1 to 0, and then 5 is written there.
callpush 3−1empty05132topreturnedpush 3: top moves up to slot 1, write 3
callpush 3
top1
There is room, so top moves up first, from 0 to 1, and then 3 is written there.
callpeek−1empty05132topreturned3peek: return the value at slot 1, which is 3
callpeek
top1
The newest element is at index top = 1, so peek returns 3 and changes nothing.
callpop−1empty05132topreturned3pop: top moves down to slot 0, 3 is out
callpop
top0
top drops from 1 to 0. The 3 is still in the array (shown faded), but no method reads above top, so it is no longer on the stack.
callisEmpty−1empty05132topreturned3falseisEmpty: top is 0, not −1 → false
callisEmpty
top0
top is 0, so 1 element is stored and the answer is false.
callisFull−1empty05132topreturned3falsefalseisFull: top is 0, last index is 2 → false
callisFull
top0
The last index is 2 and top is only 0, so there is still room: false.
callpush 8−1empty05182topreturned3falsefalsepush 8: top moves up to slot 1, write 8
callpush 8
top1
There is room, so top moves up first, from 0 to 1, and then 8 is written there, over the old 3 that a pop left behind.
callpush 1−1empty051821topreturned3falsefalsepush 1: top moves up to slot 2, write 1
callpush 1
top2
There is room, so top moves up first, from 1 to 2, and then 1 is written there.
callisFull−1empty051821topreturned3falsefalsetrueisFull: top is 2, the last index → true
callisFull
top2
top equals n − 1 = 2: every slot holds an element, so the answer is true.
callpush 6−1empty051821topreturned3falsefalsetruepush 6: top is on the last slot → full, ignore
callpush 6
top2
top is 2, which is n − 1: every slot is in use. Writing would go past the end of the array, so push returns without changing anything.
callpeek−1empty051821topreturned3falsefalsetrue1peek: return the value at slot 2, which is 1
callpeek
top2
The newest element is at index top = 2, so peek returns 1 and changes nothing.
call−1empty051821topreturned3falsefalsetrue1returned in order: 3, false, false, true, 1
returned[3, false, false, true, 1]
Every call touched at most one slot and compared top once. The values returned, in order, are 3, false, false, true, 1.
05

Common pitfalls

Writing before moving top

✗ Wrong
self.arr[self.top] = x
self.top += 1
✓ Right
self.top += 1
self.arr[self.top] = x

With top at −1, the first write goes to index −1. Python quietly treats that as the last slot, and C++ or Java write out of bounds. With n = 3, push 5 then peek returns 0 instead of 5.

Testing full against n instead of n − 1

✗ Wrong
def isFull(self):
    return self.top == len(self.arr)
✓ Right
def isFull(self):
    return self.top == len(self.arr) - 1

top is the index of the last used slot, so a full array has top == n - 1. With n = 1, push 9 then push 4 gets past the check and writes to index 1, which does not exist.

Reading the top without the empty check

✗ Wrong
def peek(self):
    return self.arr[self.top]
✓ Right
def peek(self):
    if self.isEmpty():
        return -1
    return self.arr[self.top]

On an empty stack top is −1. Python reads the last slot and returns an old value: with n = 2, push 3, push 7, pop, pop, peek returns 7 instead of −1. Java throws an exception.

06

Complexity

Time
O(1)
Space
O(n)
Each method does one comparison and at most one array access, whatever the number of stored elements. The array of n slots is allocated once in the constructor.
07

Implement Stack using Arrays FAQ

What if the stack has to grow beyond n?

When the array is full, allocate one twice as large, copy the elements across and carry on. A copy costs O(n), but doubling makes copies rare, so pushes stay O(1) on average. Python's list, C++'s vector and Java's ArrayList grow this way.

Should a stack use an array or a linked list?

An array keeps elements side by side in memory, which is fast to scan and needs no extra pointer per element, but it has a capacity. A linked list never fills up, at the cost of one pointer per node and a memory allocation on every push.

Why does the queue version need more than one index?

A queue adds at one end and removes at the other, so both ends move and eventually reach the end of the array. Implement Queue using Arrays tracks the front and the size and wraps around to index 0; a stack works at one end only and never wraps.