Front and back
- Algorithms course
- Beginner
- Lesson 67/80
- 4 min
Manage front and rear pointers.
Front and back
In a queue, front is the next element to be removed, back is the last added. These two ends define FIFO.
Looking at front (peek) lets you see the next element without removing it. This is an O(1) operation.
Queue use cases
Queue is used in BFS, printer queues, task schedulers and message queues.
BFS uses a queue to traverse a graph layer by layer. Each node adds its neighbors to the queue.
Practice Show front
Write queue_front(queue). Return the front element without removing. Print 8 with print(queue_front([8, 16, 24])).
Starter code
def queue_front(queue):
# Show frontSample solution
def queue_front(queue):
# Show front
return queue[0]
print(queue_front([8, 16, 24]))Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Front and back: match the terms
| Term | Meaning |
|---|---|
front |
Front |
back |
Back |
BFS |
Graph traversal |
peek |
Show front |
2 Which algorithm uses a queue?
- BFS Correct answer
- DFS
- Binary search
- Bubble sort
Explanation: BFS uses a queue.
3 Front
The next element to remove is the ____.
The next element to remove is the front.
Explanation: front is right.