algoritmauzmanı
Sign in
TREN
4.1Stack with an Array
Lesson 4.1.4

Peek: looking at the top

Sometimes you want to know what is on top without taking it off. For example, when checking parentheses you look at the type of the last opening bracket. does exactly that: it returns the top value and leaves the alone. Some books call it top.

What you will learn
  • The one difference between peek and pop
  • Why peek still needs a check on an empty stack
  • Why calling peek several times in a row always gives the same value
4 minTime O(1)Memory O(1)C · Java · Python

1Idea

Peek is the first half of pop: it checks for an empty stack and reads items[top]. It does not decrement top. So the stack stays the same, and no matter how many times you call peek you get the same value.

An empty stack has no top to read; items[-1] is not a valid index. So peek also reports an : C returns false, Java throws an IllegalStateException and Python raises an IndexError.

Peek and isEmpty are the two queries that do not change the stack. Algorithms that use a stack often check isEmpty first, then peek, and only then pop.

2Step by step

The drawing first peeks at a stack holding 3, 8 and 5, then tries the same on an empty stack.

30815201234-1top2top5valuetop
  1. Start. The stack holds 3, 8 and 5, and top is 2.
  2. isEmpty is checked: top is not -1, so we go on.
  3. items[2] is read: 5. In C it is written to *value; Java and Python return it.
  4. Peek is done. top is still 2 and 5 is still on top. Call peek again and you get 5 again.
  5. Peek on an empty stack: top is -1 and isEmpty returns true. There is nothing to read; C returns false, Java and Python throw an error.

#define CAPACITY 5 struct Stack {    int items[CAPACITY];    int top;}; void create(struct Stack* s) {    s->top = -1;} bool isEmpty(struct Stack* s) {    return s->top == -1;} bool peek(struct Stack* s, int* value) {    if (isEmpty(s)) {        return false;  // underflow    }    *value = s->items[s->top];  // top does not change    return true;}
class ArrayStack {    int[] items;    int top = -1;     ArrayStack(int capacity) {        items = new int[capacity];    }     boolean isEmpty() {        return top == -1;    }     int peek() {        if (isEmpty()) {            throw new IllegalStateException("stack is empty");        }        return items[top];  // top does not change    }}
class ArrayStack:    def __init__(self, capacity):        self.items = [None] * capacity        self.top = -1     def is_empty(self):        return self.top == -1     def peek(self):        if self.is_empty():            raise IndexError("stack is empty")        return self.items[self.top]  # top does not change

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

One comparison and one read. It does not depend on the number of elements.

Memory
O(1)

No extra space is used.

Pop is O(1) too; the difference between them is not time but whether the stack changes.

4Common mistake

A common mistake is using pop just to look at the top:

pop(&s, &value);if (value > 0) { ... }  // the element has left the stack

You did see the value, but the element is also gone from the stack. If it should stay, you have to push it back, and forgetting that is a silent bug. Use peek to look and pop to remove.

5Try it

A stack holds 2, 6, 4 from bottom to top. You call peek(), peek(), pop(), peek(). What does the last peek return?

Show the answer

The answer is B. The two peeks do not change the stack and both return 4. Pop removes 4. The new top is 6, so the last peek returns 6.

If peek skips the empty check, what happens on an empty array stack?

Show the answer

The answer is B. Since top is -1, items[-1] is read. C does not check it, Java throws an ArrayIndexOutOfBoundsException, and Python treats -1 as the last element and quietly returns a wrong value.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.