Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Check whether a string of brackets ()[]{} is balanced.

Problem: Check whether a string of brackets ()[]{} is balanced.
def balanced(s):
    pair = {')': '(', ']': '[', '}': '{'}
    st = []
    for ch in s:
        if ch in pair:
            if not st or st.pop() != pair[ch]:
                return False
        else:
            st.append(ch)
    return not st
print(balanced("{[()()]}"), balanced("([)]"), balanced("(("))
What is printed?
  1. A. True True False
  2. B. True False False
  3. C. True False True
  4. D. False False False

Correct answer: B. True False False

Push openers; a closer must match the most recent opener. "([)]" closes '(' while '[' is on top → False. "((" never fails during the scan but leaves items on the stack, so the final 'return not st' check makes it False – forgetting that check gives True. O(n).

More Coding Interview Problems questions

Exams that ask this topic