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)))- A. 3 5
- B. 4 3
- C. 3 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A 2-D prefix-sum table answers rectangle queries in O(1). For the 4 × 4 matrix (rows separated by ';', 0-based) 1 3 7 6; 6 8 8 6; 1 9 7 8…
- How many contiguous subarrays of [3, −2, 5, 0, −2, 1, 4, 5, 0] have sum exactly 5? (Prefix sums with a hash map of prefix-sum frequencies.)
- A circular queue in an array of size 5 keeps one slot empty to tell full from empty (front = rear means empty; (rear + 1) mod 5 = front…
- Insertion sort (ascending; shift larger elements right, one key comparison per inner-loop test, the loop stops at the first element ≤ the…
- What is the minimum number of swaps (of any two elements) needed to bring all the 1s of [1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1] together into…
- Can a string become a palindrome by deleting at most one character? Two pointers try skipping either side on the first mismatch. What is…