Valid Parentheses solution explained

The Valid Parentheses solution uses a stack: push every opening bracket, and on every closing bracket pop the top and check that it is the matching opener. The string is valid only if no check fails and the stack is empty at the end, which takes O(n) time and up to O(n) memory.

By Published 7 min read

What the problem asks

You get a string that contains only three kinds of brackets: round, square and curly, each with an opening and a closing character. Decide whether the string is well formed. Well formed means every opening bracket is eventually closed by a bracket of the same kind, and brackets close in the reverse order they opened, so an inner pair always finishes before the outer one does.

Examples written for this page
InputValid?Reason
{()[]}YesThe round and square pairs both close inside the curly pair
{(})NoThe curly pair closes while the round one inside it is still open
((NoTwo openers are never closed
]NoA closer arrives with nothing open
(){}[]YesThree separate pairs side by side
Examples written for this page. Scroll sideways on a small screen.

Two quick questions are worth asking. Is an empty string valid? It usually is, because nothing is unbalanced. Can the string contain other characters, such as letters or operators? If so, the usual choice is to skip them, but confirm before you assume.

Where it shows up in interviews

This is a common first problem in phone screens and early rounds because it checks one idea cleanly: do you recognize that nesting is a last-in, first-out structure? A counter alone fails as soon as there is more than one bracket type, and candidates who start counting usually discover that halfway through. Interviewers also use it to see how you handle a string that ends early or closes something that was never opened.

Follow-up questions

  • Only one bracket type. Then a single integer depth is enough: add one for an opener, subtract one for a closer, fail if it goes negative, and require zero at the end. That is O(1) extra space.
  • Fewest insertions to make it valid. Track unmatched openers and unmatched closers as you scan; their sum is the answer for a single bracket type.
  • Longest valid stretch. Push indexes instead of characters, and measure distances when a pair closes. This is a harder cousin and a common next question.
  • Generate every valid string of n pairs. That switches the topic to backtracking with a count of how many openers and closers remain.
  • Matching HTML or XML tags. The same stack works when each opener is a tag name instead of a single character.

A slow but correct first answer

Any balanced string contains at least one adjacent pair such as () with nothing between them. Delete such pairs again and again. If the string shrinks to nothing, it was balanced; if the deletions stop with characters left over, it was not. Each sweep is O(n) and you may need about n/2 sweeps, so the total is O(n²). It is a fine thing to mention, mostly to show why a single scan is better.

def balanced_by_erasing(text):
    previous = None
    while previous != text:
        previous = text
        text = text.replace("()", "").replace("[]", "").replace("{}", "")
    return text == ""
Repeated deletion: correct, but O(n²) in the worst case.

The stack solution

Read left to right. When you see an opener, push it. When you see a closer, the opener it must match is the most recent one still waiting, which is the top of the stack. If the stack is empty, or the top is a different kind, the string is invalid right away. After the last character, any opener left on the stack was never closed, so the string is valid only when the stack is empty.

A small lookup table keeps the code free of a long chain of if statements, and it makes adding a fourth bracket kind a one-line change. The Python version below uses a neat twist: when it sees an opener it pushes the closer it now expects, so the check on a closer is a plain equality test. The JavaScript version maps each closer back to its opener instead. Both are standard; pick the one you can explain fastest.

EXPECTED_CLOSER = {"(": ")", "[": "]", "{": "}"}

def is_well_formed(text):
    owed = []  # closers still owed, most recent on top
    for ch in text:
        if ch in EXPECTED_CLOSER:
            owed.append(EXPECTED_CLOSER[ch])
        elif ch in ")]}":
            if not owed or owed.pop() != ch:
                return False
    return len(owed) == 0
Python: push the expected closer, compare on the way out. O(n) time, O(n) space.
const PARTNER = { ")": "(", "]": "[", "}": "{" };

function isWellFormed(text) {
  const waiting = [];
  for (const ch of text) {
    if (ch === "(" || ch === "[" || ch === "{") {
      waiting.push(ch);
    } else if (ch in PARTNER) {
      if (waiting.length === 0 || waiting.pop() !== PARTNER[ch]) return false;
    }
  }
  return waiting.length === 0;
}
JavaScript: the same scan with an array as the stack.

Both versions skip characters that are not brackets, which matches the most common clarification. If the interviewer says the input holds brackets only, the code still works unchanged. One small speed-up applies only when the input is brackets alone: a string of odd length can never be balanced, so you may return false before scanning. With other characters mixed in, such as a(b)c, that shortcut is wrong. Mention it, but do not lead with it.

Cost of each approach

Time and extra memory
ApproachTimeExtra memoryNotes
Delete adjacent pairs until stableO(n²)O(n) for new stringsEasy to explain, slow on long input
Stack of openersO(n)O(n) in the worst caseThe expected answer
Depth counterO(n)O(1)Correct only when there is a single bracket kind
Time and extra memory. Scroll sideways on a small screen.

The stack's worst case is a string of nothing but openers, where every character is pushed. For balanced input the stack never holds more than the deepest nesting level.

Inputs that break careless code

  • A closer as the very first character, like )(. Popping an empty stack crashes in some languages and returns undefined in others.
  • Leftover openers at the end, like [[]. Code that only checks for mismatches returns true by mistake.
  • Interleaved kinds, like {(}), where counts are balanced but order is not.
  • An empty string, which most interviewers treat as valid.
  • Very deep nesting, such as ten thousand openers followed by ten thousand closers. A recursive solution may hit the recursion limit; the loop does not.

Common slips

  • Using three separate counters, one per kind. Counters cannot see order, so {(}) passes.
  • Forgetting the final emptiness check.
  • Comparing a closer with the opener on top of the stack directly, which never matches, instead of going through the lookup table.
  • Peeking at the top before checking that the stack has anything in it.
  • Explaining the code line by line without ever saying why a stack fits. The one-sentence reason is what the interviewer is listening for.

Saying it out loud

Fictional example

A short spoken explanation
Candidate
The key fact is that whatever opened last has to close first, which is exactly how a stack behaves.
Candidate
So I push openers. For a closer I check two things: that the stack is not empty and that the popped opener is its partner. Either failure means invalid.
Candidate
At the end I return whether the stack is empty, because leftovers were never closed. That is one pass, linear time, and linear space in the worst case when everything is an opener.

Where to go next

Merge Intervals is the natural next step: it also tracks what is still open, but with sorted ranges instead of characters. Binary Tree Level Order Traversal shows the stack's sibling, the queue, which serves first-in, first-out order. For the hash map warm-up that often comes before this problem, see Two Sum, and for every walkthrough, the coding problems hub.

Using Natively in practice

Natively runs on Mac and Windows and can read a bracket problem like this from a screenshot during practice, then suggest the stack idea and the edge cases worth testing. It also keeps a transcript of a mock session on your computer, so you can check afterward whether you explained why the stack fits or only described the code. See how the AI interview assistant works.

Questions people ask

What is the best way to solve Valid Parentheses?

Scan the string once with a stack. Push each opening bracket; on a closing bracket, the stack must be non-empty and its top must be the matching opener. The string is valid if the stack is empty at the end. That is O(n) time.

Why does a counter not work for Valid Parentheses?

A counter tracks how many brackets are open but not their order or kind. A string such as {(}) has balanced counts yet closes the curly bracket while the round one is still open.

Is an empty string valid?

In the usual version, yes, because nothing is left unclosed. Confirm it with the interviewer, since it is a one-line difference.

What is the space complexity of the stack solution?

O(n) in the worst case, when the string is all opening brackets. For a single bracket type, a depth counter brings it down to O(1).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP