LeetCode Blind 75: Valid Parentheses


Greetings, traveler!

One of the most common interview questions from the LeetCode Blind 75 list is Valid Parentheses.
It’s short, elegant, and tests a candidate’s understanding of one of the most important data structures — the stack.

Problem Overview

Given a string containing only the characters '(', ')', '{', '}', '[', and ']',
determine whether the input string is valid.

A string is valid if:

  1. Every opening bracket has a corresponding closing bracket of the same type.
  2. Brackets are closed in the correct order.
  3. Every closing bracket matches the most recent unmatched opening one.

Example 1

Input: s = "()"
Output: true

Example 2

Input: s = "()[]{}"
Output: true

Example 3

Input: s = "(]"
Output: false

Example 4

Input: s = "([)]"
Output: false

1. Understanding the Idea

The core concept is to use a stack — a data structure that works in a Last-In, First-Out (LIFO) fashion.
We push each opening bracket onto the stack and pop it when we find a matching closing one.

If at any point the brackets don’t match, or we try to pop from an empty stack, the string is invalid.
At the end, the stack must be empty — meaning all brackets have been properly closed.

2. Swift Implementation

func isValid(_ s: String) -> Bool {
    var stack: [Character] = []
    let pairs: [Character: Character] = [")": "(", "}": "{", "]": "["]
    
    for ch in s {
        if pairs.values.contains(ch) {
            // Opening bracket — push to stack
            stack.append(ch)
        } else if let match = pairs[ch] {
            // Closing bracket — check the last opened
            if stack.isEmpty || stack.removeLast() != match {
                return false
            }
        }
    }
    
    return stack.isEmpty
}

3. How It Works (Step by Step)

Let’s walk through an example:

s = "{[()]}"
StepCharActionStackComment
1{push{open curly brace
2[push{ [open square bracket
3(push{ [ (open round bracket
4)pop{ [matches (
5]pop{matches [
6}pop[] (empty)matches {

At the end, the stack is empty → valid string.

4. The Key Line Explained

This part is the core of the solution:

if stack.isEmpty || stack.removeLast() != match {
    return false
}

Let’s break it down:

  1. stack.isEmpty — prevents an “index out of range” crash.
    If the stack is empty and we find a closing bracket, the sequence is invalid (e.g. ")(").
  2. stack.removeLast() != match
    removes the last opening bracket from the stack and checks if it matches the current closing one.
    Even if the comparison fails, the removal still happens — which is exactly what we want:
    once we try to close a bracket, that opening is no longer “active”.

In Swift, removeLast() both returns and removes the element,
so this line is effectively performing the “pop and compare” operation in one expression.

This one-liner combines safety (empty-check) and correctness (pair matching), making it a concise and idiomatic way to validate parentheses in Swift.

5. Example: Invalid Case

Let’s test:

s = "([)]"
StepCharStackActionComment
1((pushopen round
2[([pushopen square
3)([pop [( → return falsemismatched pair

The function returns false as soon as the mismatch is detected.

6. Complexity

MetricValue
TimeO(n) — each character is processed once
SpaceO(n) — in the worst case, all are opening brackets