Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

A checker counts how many strings are balanced over (), [] and {}. Version A uses a stack; version B only keeps one counter of open minus close brackets. What is printed?

A checker counts how many strings are balanced over (), [] and {}. Version A uses a stack; version B only keeps one counter of open minus close brackets. What is printed?
def by_stack(s):
    st, pair = [], {")": "(", "]": "[", "}": "{"}
    for ch in s:
        if ch in "([{": st.append(ch)
        elif not st or st.pop() != pair[ch]: return False
    return not st
def by_count(s):
    c = 0
    for ch in s:
        c += 1 if ch in "([{" else -1
        if c < 0: return False
    return c == 0
ws = ['[{}](', '{[()()]}', '(([]))', '{(})', '([]{})', ')(']
print(sum(map(by_stack, ws)), sum(map(by_count, ws)))
  1. A. 3 5
  2. B. 4 3
  3. C. 3 4
  4. D. 5 4

Correct answer: C. 3 4

A single counter cannot see the bracket TYPE or crossing like ([)], so it accepts strings the stack rejects. Output: 3 4.

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

Exams that ask this topic