Data Structures & AlgorithmsModerateTCS NQT · stack basics

Problem: Check bracket balance for '([]{})' and '([)]' with a stack. What is printed?

Problem: Check bracket balance for '([]{})' and '([)]' with a stack. What is printed?
def ok(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    st = []
    for c in s:
        if c in '([{':
            st.append(c)
        elif not st or st.pop() != pairs[c]:
            return False
    return not st
print(ok('([]{})'), ok('([)]'))
What is printed?
  1. A. True True
  2. B. False False
  3. C. False True
  4. D. True False

Correct answer: D. True False

The first string nests correctly, while in '([)]' the ')' closes a '(' that is not on top of the stack. The stack check catches interleaving, not just count mismatches.

More Coding Interview Problems questions

Exams that ask this topic