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 Kotlin 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.kt
import java.util.ArrayDeque
fun render(values: List<Int>) = values.joinToString(" -> ")
fun main() {
val queue = ArrayDeque<Int>()
for (value in listOf(10, 20, 30)) queue.addLast(value)
val removed = mutableListOf<Int>()
while (!queue.isEmpty()) removed.add(queue.removeFirst())
println(render(removed))
}
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- Kotlin imports
java.util.ArrayDequeand createsval queue = ArrayDeque<Int>(); the reference is not rebound, but the deque contents mutate. - Enqueue uses
queue.addLast(value)for values fromlistOf(10, 20, 30), preserving insertion order at the back of the deque. - Removed values are collected in
val removed = mutableListOf<Int>(), so the output list mutates separately from the queue. - Dequeue uses
queue.removeFirst()insidewhile (!queue.isEmpty()); the emptiness guard avoids the exception path for removing from an empty deque. - Values are non-null
Ints throughout; no nullable queue result is used. - The trace shows the queue moving from
[]to[10, 20, 30], then removing10with queue[20, 30], and finally removed[10, 20, 30]with queue[]. render(values: List<Int>)usesjoinToString(" -> "), andprintln(render(removed))prints10 -> 20 -> 30.