Skip to content
Veltoryx Technologies
FreeProblem 55● EasyLeetCode #20 ↗4 min readUpdated 30 October 2026

Valid Parentheses

Determine if a string of bracket characters has every opener closed by the same type in proper nested order using a stack of expected closers.

01The problem

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.
InputOutputWhy
"()[]{}"trueEvery opener is matched immediately by its corresponding closer
"(]"falseRound opener '(' is closed by square bracket ']'
"([)]"falseOut of order: '[' was opened after '(', so it must close first

Constraints: 1 <= s.length <= 10^4, string consists solely of parentheses '()[]{}'.

02How to spot it

  • The problem demands that the most recently opened bracket must be the first one closed.
  • This is textbook Last In, First Out (LIFO) ordering.
  • Nesting can be arbitrarily deep.
  • An opener creates an expectation: when we see '(', we expect a ')'. Pushing the expected closer onto a stack turns matching into a single equality check.

So: stack of expected closers.

03Pseudocode

text
stack = empty
for c in s:
  if c is an opener: push its closer
  elif stack empty or pop() != c:
    return false
return stack is empty
  1. See an opener? Remember which closer you now expect.
  2. See a closer? It must match the latest expectation at the top of the stack.
  3. At the end, nothing may remain open.

04Watch it work

Visualizer · step through the algorithms = "()[]{}"

s

(0
)1
[2
]3
{4
}5

expected closers (top on right)

Initialize an empty stack. As we read openers, we push the matching closer we expect.

Pseudocode

  1. stack = empty
  2. for c in s:
  3. if c is an opener: push its closer
  4. elif stack empty or pop() != c:
  5. return false
  6. return stack is empty

Variables

stack
step 1 / 8

05Step-by-step dry run

  1. 1

    s

    (0
    )1
    [2
    ]3
    {4
    }5

    expected closers (top on right)

    Initialize an empty stack. As we read openers, we push the matching closer we expect.

    stack =

  2. 2

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    )0
    top

    Saw opener `(`. Push expected closer `)` onto the stack.

    c = (expected = )stackSize = 1

  3. 3

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    Saw closer `)` matching expected `)`. Popped successfully.

    c = )matched = )stackSize = 0

  4. 4

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    ]0
    top

    Saw opener `[`. Push expected closer `]` onto the stack.

    c = [expected = ]stackSize = 1

  5. 5

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    Saw closer `]` matching expected `]`. Popped successfully.

    c = ]matched = ]stackSize = 0

  6. 6

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    }0
    top

    Saw opener `{`. Push expected closer `}` onto the stack.

    c = {expected = }stackSize = 1

  7. 7

    s

    (0
    )1
    [2
    ]3
    {4
    }5
    c

    expected closers (top on right)

    Saw closer `}` matching expected `}`. Popped successfully.

    c = }matched = }stackSize = 0

  8. 8

    s

    (0
    )1
    [2
    ]3
    {4
    }5

    expected closers (top on right)

    Finished scanning. Stack is empty: all brackets matched and closed properly. Return true.

    valid = true

06Java solution

ValidParentheses.java
import java.util.ArrayDeque;
import java.util.Deque;

public class ValidParentheses {
    public static boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c == '(') stack.push(')');
            else if (c == '[') stack.push(']');
            else if (c == '{') stack.push('}');
            else if (stack.isEmpty() || stack.pop() != c) return false;
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isValid("()[]{}"));
        System.out.println(isValid("([)]"));
    }
}
Expected output
true
false

07Why it works

Pushing the expected closer instead of the opener simplifies the verification step. When we see '(', we push ')'. When a closing character c arrives:

  • If the stack is empty, there is no opener waiting for this closer (e.g. ")"). Return false.
  • If stack.pop() != c, the most recently opened scope was closed by the wrong type (e.g. "(]"). Return false.
  • If they match, the inner scope is cleanly resolved.

After examining all characters, any remaining element on the stack indicates an unclosed opener (e.g. "((("). Checking stack.isEmpty() handles this edge case.

08Time and space

  • Time complexity: O(n). We iterate through the string of length n once. Each character triggers at most one push or pop, both O(1) operations.
  • Space complexity: O(n). In the worst case (e.g. "(((((("), the stack holds n expected closer characters.

09Edge cases

  • Odd length string: Immediately invalid (cannot be evenly paired).
  • String starting with closer (e.g. ")("): First character hits stack.isEmpty(), immediately returning false.
  • All openers (e.g. "((("): Loop finishes with non-empty stack, stack.isEmpty() correctly returns false.
  • Single character (e.g. "["): Stack has 1 element, returns false.

10Common mistakes

  • Using counters instead of a stack. A simple counter tracks quantity, but fails on ordering (e.g. "([)]" has equal counts of each type, but invalid nesting).
  • Using legacy java.util.Stack. Stack extends Vector, which synchronizes every method call and slows down execution. Use ArrayDeque.
  • Forgetting the final stack.isEmpty() check. Returning true at the end of the loop without checking whether the stack is empty wrongly accepts incomplete strings like "(()".

11Other approaches

ApproachTimeSpaceUse when
Stack of expected closersO(n)O(n)Standard, optimal interview solution
Replace "()", "[]", "{}" in stringO(n^2)O(n)Quick to write in a script, unacceptable in interview

12In the interview

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why does pushing the expected closing bracket make the code cleaner?

  2. 2. What happens when evaluating the string "([)]"?

14Solve it yourself

Try implementing a function that also returns the 0-based index of the first invalid bracket:

  1. Push an object or pair (expectedCloser, index) onto the stack.
  2. Return the offending index if mismatch occurs, or the index of the first unclosed opener if the stack remains non-empty.