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?
  1. A. 6 3 5
  2. B. 6 4 5
  3. C. 6 3 4
  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

Exams that ask this topic