← DSA practice

Valid Parentheses

EasyStackO(n) time · O(n) space

The problem

Given a string of ()[]{}, decide whether the brackets are closed in the correct order.

"()[]{}"  →  true
"(]"      →  false
"([)]"    →  false
Stuck? Open one hint

The last bracket you opened must be the first one you close.

Show the worked solution

"Last opened, first closed" is the definition of a stack. Push every opening bracket. On a closing bracket, pop and check it matches; if the stack is empty when you need to pop, it is invalid.

At the end the stack must be empty — otherwise something was never closed. Both failure cases matter, and candidates often forget the second one.

fun isValid(s: String): Boolean {
    val pairs = mapOf(')' to '(', ']' to '[', '}' to '{')
    val stack = ArrayDeque<Char>()
    for (c in s) {
        if (c in pairs.values) stack.addLast(c)
        else if (stack.removeLastOrNull() != pairs[c]) return false
    }
    return stack.isEmpty()
}

O(n) time · O(n) space