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)putsxon top;pop()removes the top element.peek()returns the top element, or −1 if the stack is empty.isEmpty()andisFull()say whether the stack holds 0 ornelements.
A pop or peek can arrive while the stack is empty, so those calls must leave it unharmed.
- 1 <= n <= 10³ (array size)
- 1 <= number of queries <= 10³
- 0 <= x <= 10⁵
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
topup or down by one slot. - Pop erases nothing. A value above
topis invisible to every method, and the next push writes over it.
"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.
Approach
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.
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.
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.
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.
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.
Code in Python, C++ and Java
top starts at −1, one below index 0, so the first push will land on index 0 with no special case.top moves up first, from −1 to 0, and then 5 is written there.top moves up first, from 0 to 1, and then 3 is written there.top = 1, so peek returns 3 and changes nothing.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.top is 0, so 1 element is stored and the answer is false.top is only 0, so there is still room: false.top moves up first, from 0 to 1, and then 8 is written there, over the old 3 that a pop left behind.top moves up first, from 1 to 2, and then 1 is written there.top equals n − 1 = 2: every slot holds an element, so the answer is true.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.top = 2, so peek returns 1 and changes nothing.top once. The values returned, in order, are 3, false, false, true, 1.top starts at −1, one below index 0, so the first push will land on index 0 with no special case.top would drop to −2 and the next push would write to index −1.top is −1, so there is no element to read. Returning −1 is the rule for an empty stack; reading arr[-1] instead would return an old value or crash.top is −1, so no slot is in use and the answer is true.top moves up first, from −1 to 0, and then 9 is written there.top equals n − 1 = 0: every slot holds an element, so the answer is true.top is 0, which is n − 1: every slot is in use. Writing would go past the end of the array, so push returns without changing anything.top = 0, so peek returns 9 and changes nothing.top once. The values returned, in order, are −1, true, true, 9.Common pitfalls
Writing before moving top
self.arr[self.top] = x self.top += 1
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
def isFull(self):
return self.top == len(self.arr)def isFull(self):
return self.top == len(self.arr) - 1top 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
def peek(self):
return self.arr[self.top]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.
Complexity
n slots is allocated once in the constructor.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.