Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (balanced brackets with a counter only)

What is printed? (balanced brackets with a counter only)
def by_counter(s):
    c = 0
    for ch in s:
        c += 1 if ch == '(' else -1
        if c < 0: return False
    return c == 0
print(by_counter("(()())"), by_counter("())(()"), by_counter(")("))
  1. A. True True False
  2. B. True False True
  3. C. True False False
  4. D. False False False

Correct answer: C. True False False

With a single bracket type a counter suffices: it must never go negative and must end at 0. "())(()" dips to −1 after the third character. With several bracket types a stack is required, because "([)]" has balanced counts but wrong nesting.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic