algoritmauzmanı
Sign in
TREN
5.1Queue with an Array
Lesson 5.1.4

Peek: looking at the front

hands back the value of the element at the front of a but does not remove it. It is like checking who is next in line. In an array queue, peek is the first two steps of : the empty check and the read. is not increased.

What you will learn
  • The one difference between peek and dequeue
  • Why peek also checks for an empty queue
  • When peek is useful
4 minTime O(1)Memory O(1)C · Java · Python

1Idea

Peek reads items[front] and returns it. front and do not change, and the queue stays the same. Call peek ten times in a row and you get the same value ten times. Dequeue moves on to the next element on every call.

When the queue is empty, the cell at front is not part of the queue; it may hold an old value or garbage. So peek also checks isEmpty first. If the queue is empty, C returns false, Java throws IllegalStateException and Python raises IndexError.

Peek is used to look at the next element before deciding. Example: in a printer queue, look at the page count of the front job and check whether the printer has enough paper. If it does not, the job is not removed from the queue and keeps its turn.

Some sources call peek front or getFront. Java's Queue interface also uses the name peek.

2Step by step

In the drawing, 3 has already been removed from the queue; cell 0 is faded. The queue holds 8 and 5. First a peek runs, then a peek is tried on an empty queue.

308152341front3front2rear8valuefrontrear
  1. The start. front is 1 and rear is 2. The queue holds 8 and 5. peek is called.
  2. isEmpty is checked: 2 < 1 is false. The queue is not empty.
  3. items[front] is read: value becomes 8.
  4. The function hands back 8. front is still 1: 8 stays in the queue, and the next dequeue will still remove 8.
  5. After the queue is emptied, peek is tried: front is 3 and rear is 2. isEmpty returns true; C returns false, Java and Python throw an error.

#define CAPACITY 5 struct Queue {    int items[CAPACITY];    int front;    int rear;}; void create(struct Queue* q) {    q->front = 0;    q->rear = -1;} bool isEmpty(struct Queue* q) {    return q->rear < q->front;} bool peek(struct Queue* q, int* value) {    if (isEmpty(q)) {        return false;  // queue is empty    }    *value = q->items[q->front];  // front does not change    return true;}
class ArrayQueue {    int[] items;    int front = 0;    int rear = -1;     ArrayQueue(int capacity) {        items = new int[capacity];    }     boolean isEmpty() {        return rear < front;    }     int peek() {        if (isEmpty()) {            throw new IllegalStateException("queue is empty");        }        return items[front];  // front does not change    }}
class ArrayQueue:    def __init__(self, capacity):        self.items = [None] * capacity        self.front = 0        self.rear = -1     def is_empty(self):        return self.rear < self.front     def peek(self):        if self.is_empty():            raise IndexError("queue is empty")        return self.items[self.front]  # front 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. The length of the queue does not matter.

Memory
O(1)

No extra space is used.

Peek on a stack looks at the top; peek on a queue looks at the front. Both are O(1).

4Common mistake

A common mistake is skipping the empty check:

def peek(self):    return self.items[self.front]  # wrong: the queue may be empty

On an empty queue this code raises no error and quietly returns a wrong value. A new queue gives None. If elements were added and removed, front may have gone past the end of the array and an IndexError comes from somewhere else. Either way, the caller cannot tell that the queue was empty.

5Try it

The queue holds 6, 1 and 9 in that order. What do peek, peek, dequeue, peek give?

Show the answer

The answer is A. Peek does not remove the front element, so it gives 6 twice. Dequeue removes 6. The next peek gives the new front element, 1.

What is the difference between peek and dequeue?

Show the answer

The answer is B. Both read items[front] and both check for an empty queue first. Only dequeue adds one to front, which takes the element out of the queue.

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