Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
Basic Implementation
basic.rb
queue = []
[10, 20, 30].each { |value| queue.push(value) }
removed = []
removed << queue.shift until queue.empty?
puts removed.join(" -> ")
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- The queue is a Ruby
Array, starting asqueue = []. - Enqueue uses
queue.push(value)inside[10, 20, 30].each, so new values are appended at the back in that order. - Dequeue uses
queue.shift, which removes and returns the front element while mutating the array. removed << queue.shift until queue.empty?keeps shifting only while the queue has values, so this source never relies onshiftreturningnilfrom an empty array.- FIFO order is visible in the trace:
[10, 20, 30]becomes[20, 30]after removing10, then becomes empty after removing20and30. removedis another Ruby array that records the returned values as[10, 20, 30].puts removed.join(" -> ")prints the deterministic output10 -> 20 -> 30.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.