AniUI Academy

Valid Parentheses Matcher

easyData Structures+150 XPFrontend AlgoArena

Bracket matching is the textbook use case for a stack — the same algorithm that powers syntax highlighting, JSON validators, and expression parsers.

Given a string containing only (), [], and {}, return whether every opener is closed by the matching type and in the correct order. ([]) is valid; ([)] is not.

Arguments

sstring
A string containing only the characters ()[]{}.

Returns

boolean — true when every opener is matched by the correct closer in order, else false.

Examples

isValidParentheses("()[]{}"); // true
isValidParentheses("{[]}");    // true
isValidParentheses("");        // true — the empty string is vacuously valid
isValidParentheses("(]");   // false — wrong closer type
isValidParentheses("([)]"); // false — correct types, wrong order
isValidParentheses("(");    // false — unclosed opener left on the stack

What it has to do

  • Return true if string brackets are valid, false otherwise.
  • Use Stack data structure.

Notes

  • After the loop finishes, the stack must be empty — a non-empty stack means openers were never closed.
  • Encountering a closer while the stack is empty is an immediate false; otherwise .pop() on [] returns undefined and can mask bugs.
Asked atGoogleAmazonMeta
Try it yourself
Loading playground...
2 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.