learn deep. ship safe.Practice testsFollow ByteMunSubscribe

easyStackStrings

Balanced Brackets

Decide whether a string of brackets is balanced: every opening bracket closed by the same type, in the right order. The standard stack question in coding rounds.

By Tests checked by DeepakJavaScript or Python

Given a string s made only of the characters ()[]{}, return true if it is balanced and false otherwise.

A string is balanced when every opening bracket is closed by the same type of bracket, and brackets close in the reverse order they were opened. An empty string is balanced.

Examples

Example 1

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

Example 2

Input: s = "([)]"
Output: false
Why: [ is closed by ) before it is closed by ]

Constraints

  • 0 <= s.length <= 10^4
  • s contains only ()[]{}

Hints

Hint 1

The most recently opened bracket must be the first one closed. Which data structure gives you the most recent item first?

Hint 2

Push opening brackets; on a closing bracket, the top of the stack must be its partner. What should be left at the end?

Solution

Show the solution (try it yourself first)

Approach: a stack

Brackets close in the reverse order they opened, which is exactly last-in, first-out, so a stack fits. Push every opening bracket. For a closing bracket, pop the top: it must be the matching opener, otherwise the string is unbalanced. Two edge cases catch most wrong answers: a closing bracket when the stack is empty, such as ")(", and leftover openers at the end, such as "(((". The string is balanced only if the stack ends empty.

def is_balanced(s):
    pair = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in pair:
            if not stack or stack.pop() != pair[ch]:
                return False
        else:
            stack.append(ch)
    return not stack

Complexity

Time O(n), one pass. Space O(n) in the worst case, when every character is an opener. A counter alone only works for a single bracket type, which is a common follow-up question.

Case 1Input: "([]{})"Expected: true
Case 2Input: "([)]"Expected: false

Run checks these 2 samples. Submit checks all 8 tests, including hidden ones.

  1. Palindrome SentenceStrings · Two pointers
    easy
  2. Longest Substring Without RepeatsStrings · Sliding window · Hash map
    medium
  3. Group AnagramsStrings · Hash map · Sorting
    medium
  4. Pair with Target SumArrays · Hash map
    easy