Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
The replay uses the same three values in every language, so this Go DSA implementation can be compared directly with the rest of the DSA track.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.
Visual walkthrough
Basic Implementation
basic.go
package main
import (
"fmt"
"strings"
)
func render(values []int) string {
parts := make([]string, 0, len(values))
for _, value := range values {
parts = append(parts, fmt.Sprint(value))
}
return strings.Join(parts, " -> ")
}
func main() {
queue := []int{}
for _, value := range []int{10, 20, 30} { queue = append(queue, value) }
removed := []int{}
for len(queue) > 0 { removed = append(removed, queue[0]); queue = queue[1:] }
fmt.Println(render(removed))
}
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- Go starts with
queue := []int{}and appends10,20, and30;appendmay grow the backing array, but the visible queue state becomes[10, 20, 30]. - Dequeue reads the front slot with
queue[0], appends that value toremoved, then advances the slice header withqueue = queue[1:]. - The loop guard
len(queue) > 0prevents an empty-slice index. Because reslicing keeps a view of the same backing array, a long-lived queue could retain dequeued storage; this tiny replay drains it immediately. - The trace records the empty queue, the enqueue batch, one front removal to
removed=[10]withqueue=[20, 30], then the remaining removals toremoved=[10, 20, 30]andqueue=[]. renderallocates a[]string, converts eachintwithfmt.Sprint, joins withstrings.Join(parts, " -> "), andfmt.Printlnprints10 -> 20 -> 30.