CodingEasy Searching & Stacks

Valid Parentheses

Asked for all developer roles

Why they ask this: The standard stack problem; it shows you can pick the right data structure for matching pairs.

Problem

Given a string s containing only the characters (, ), {, }, [ and ], return true if:

  1. every opening bracket is closed by the same type of bracket, and
  2. brackets are closed in the correct order.

Examples

text
Input: "()[]{}"   Output: true
Input: "([{}])"   Output: true
Input: "(]"       Output: false
Input: "([)]"     Output: false
Input: "(("       Output: false

Hints

    Approach

    Use a stack and a map from each closing bracket to its opening partner:

    1. For an opening bracket, push it.
    2. For a closing bracket, pop the top. If the stack was empty or the popped bracket is not the matching opener, return false.
    3. After the loop, return true only if the stack is empty (otherwise some brackets were never closed).

    Quick check: a string with an odd length can never be valid.

    Solution

    js
    function isValid(s) {
      const pairs = { ')': '(', ']': '[', '}': '{' };
      const stack = [];
    
      for (const ch of s) {
        if (ch === '(' || ch === '[' || ch === '{') {
          stack.push(ch);
        } else if (stack.pop() !== pairs[ch]) {
          return false;
        }
      }
    
      return stack.length === 0;
    }
    
    console.log(isValid('([{}])')); // true
    console.log(isValid('([)]'));   // false
    Time O(n) Space O(n)

    Can you explain this in your own words?

    Back to coding practice