Data Structures · Visualization
Deque: Push Front
Deque
Pushing to the front adds a new item before the current first item, making it the new front. Time: O(1). Space: O(1) per operation.
Big-O: Push/pop at both ends in O(1).
Deque: Push Front
DequePushing to the front adds a new item before the current first item, making it the new front. The visualizer starts from an empty deque and pushes its default value 15, so the first frame holds [15]; pushing 15 again would give [15, 15] because each call inserts ahead of whatever is already there. A deque is built so this is exactly as cheap as pushing at the back: a doubly linked list rewires two pointers, and a circular array decrements the front index modulo capacity. That keeps push-front O(1) while capacity remains, with a reallocation as the only occasional O(n) cost.
How Push Front Works
- Take the new value to add — the visualizer uses 15.
- Check capacity: a bounded circular deque must not overwrite the back when the ring is full.
- Place it before the current front item, or at index front - 1 modulo capacity.
- Update the 'front' reference to point to this new item.
- Leave the back reference alone unless the deque was empty, in which case both ends name the new item.
Push Front Worked Example
Input: pushFront(15) on the default empty deque
- The visualizer's default deque is empty, so there is no front to move aside.
- 15 becomes the only item: [15], and it is both the front and the back.
- A second pushFront(15) would insert ahead of it and produce [15, 15].
Output: [15]
Press ▶ Run to watch it step by step.
from collections import deque
d = deque()
d.append(1) # push back
d.appendleft(2) # push front
d.pop() # pop back
d.popleft() # pop front
# O(1) at both ends
# example: push front 15 on [1, 2, 3]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Push Front Time & Space Complexity
When to Use Push Front
- Adding a high-priority task to the very front of a work queue
- Implementing 'undo' by pushing the previous state to the front
- Sliding window algorithms that remove/add at the front as the window moves
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.