Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d.
Problem: Score a balanced bracket string: "()" = 1, AB = A + B, (A) = 2·A. Each innermost "()" at depth d contributes 2^d.
def score(s):
depth = res = 0
for i, c in enumerate(s):
if c == "(":
depth += 1
else:
depth -= 1
if s[i - 1] == "(":
res += 1 << depth
return res
print(score("(()(()))"), score("()(())"), score("((()))()"))What is printed?- A. 6 3 5
- B. 6 4 5
- C. 6 3 4
- D. 5 3 5
Correct answer: A. 6 3 5
Only the "()" cores produce value; every enclosing pair doubles it, so a core closed at depth d adds 2^d. "(()(()))": cores at depth 1 (2) and depth 2 (4) → 6. "()(())": 1 + 2 = 3. "((()))()": 4 + 1 = 5. O(n) time, O(1) space – no stack needed.
More Coding Interview Problems questions
- Problem: Delivery vans drive towards a depot at 20 km; a faster van that catches a slower one ahead must slow down and they arrive as one…
- Problem: Evaluate an expression of non-negative integers with + − / (no brackets, / truncates toward zero) in one pass with a stack…
- Problem: A magician reveals cards like this: show the top card, then move the next top card to the bottom; repeat. Arrange the deck so the…
- Problem: From a sorted linked list delete EVERY value that occurs more than once (keep only values that appear exactly once). python class…
- Problem: Reorder a list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place: find the middle, reverse the second half, then interleave…
- Problem: Find the area of the largest all-'1' rectangle in a binary grid by treating each row as the base of a histogram and running the…