Skip to content
PlaceNivo

Stack Easy

Valid Parentheses: Solution and Approach

Given a string of the brackets ( ) { } [ ], return true if every opening bracket is closed by the same type in the correct order.

Similar questions reported in: TCS, Infosys, Wipro, Accenture, Amazon, Cognizant

Example

Input:
s = "([]{})"
Output:
true

Brute force first

Repeatedly remove "()", "[]" and "{}" until nothing changes. This is O(n²).

The better idea

Use a stack. Push every opening bracket. For a closing bracket, the top of the stack must be its matching opener. At the end the stack must be empty.

Steps

  1. Map each closing bracket to its opener: ) → (, ] → [, } → {.
  2. For each character: if it is an opener, push it.
  3. If it is a closer, and the stack is empty or the top doesn't match, return false. Otherwise pop.
  4. Return true only if the stack is empty.

Code

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)
    return not stack

Complexity

Time: O(n)

Space: O(n) for the stack.

Edge cases to test

  • Only openers, such as "((": the stack is not empty, so false.
  • A closer first, such as ")(": the stack is empty, so false.

Solved it? Pick the next problem

Do one more problem from the same pattern today, so the idea sticks.