Kotlin ArrayDeque as a stack and a queue

kotlin.collections.ArrayDeque is a resizable circular array that supports adding and removing at both ends in amortized O(1). With addLast and removeLast it behaves as a stack (last-in, first-out). With addLast and removeFirst it behaves as a queue (first-in, first-out). removeLastOrNull and removeFirstOrNull return null instead of throwing when it is empty.

Kotlin
fun balanced(text: String): Boolean {
    val stack = ArrayDeque<Char>()
    val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
    for (ch in text) {
        when (ch) {
            '(', '[', '{' -> stack.addLast(ch)
            ')', ']', '}' -> if (stack.removeLastOrNull() != pairs[ch]) return false
        }
    }
    return stack.isEmpty()
}

fun main() {
    for (test in listOf("(a[b]{c})", "(]", "((", ")(", "")) {
        println("'$test' -> ${balanced(test)}")
    }

    val queue = ArrayDeque<String>()
    queue.addLast("Ada")
    queue.addLast("Bo")
    queue.addLast("Cy")
    val served = queue.removeFirst()
    println("$served served, ${queue.size} waiting, next is ${queue.first()}")
}
Read the full lesson