00:00

Problem Statement

Input/Output Examples

Visual Explanation

Pushing the expected closer rather than the opener makes the check a single comparison. At the end, the stack must be empty; otherwise some bracket was never closed.

Approaches

The stack approach is the standard answer. The pair-removal approach is shorter to describe but much slower.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string. The stack version reads each character once and stores at most n brackets; the removal version may rebuild the string many times.

Interview Tips and Recommended Approach

  • Check the empty stack before popping. A closer with nothing open, as in ")(", must return false, not throw.
  • Check the stack at the end. "((" never fails a comparison, but it is still unbalanced.
  • Explain why counters fail. Counting opens and closes works for one bracket type but accepts "([)]" with several types.
  • Prefer ArrayDeque to Stack. The legacy Stack class is synchronized and slower.

Recommended Approach: Stack of Expected Closers

Why: it checks the string in one pass, handles any mix of bracket types and nesting depth, and its logic is easy to justify.