Enqueue values at the back and dequeue them from the front in first-in, first-out order.

Algorithm

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))
}

The queue keeps the oldest value at the front and adds new values at the back.

Step 1 - Enqueue 10, 20, 30

New values join at the back. The oldest value, 10, stays at the front.

Queue after three enqueues: front 10, then 20, then back 30.nextnext10front2030back

Step 2 - Dequeue removes 10

Removing from the front returns 10 and makes 20 the new front.

After one dequeue: removed is 10; front moves to 20.next10removed20front30back

Complexity

  • Time: O(1) per operation with a real queue
  • Space: O(n)

Implementation notes

  • Kotlin imports java.util.ArrayDeque and creates val queue = ArrayDeque<Int>(); the reference is not rebound, but the deque contents mutate.
  • Enqueue uses queue.addLast(value) for values from listOf(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() inside while (!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 removing 10 with queue [20, 30], and finally removed [10, 20, 30] with queue [].
  • render(values: List<Int>) uses joinToString(" -> "), and println(render(removed)) prints 10 -> 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.