Data Structures & AlgorithmsVery hardProduct company OA

Problem: A string has '(', ')' and '', where '' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible open-bracket counts.

Problem: A string has '(', ')' and '*', where '*' may act as '(', ')' or nothing. Is it balanceable? Track the range [lo, hi] of possible open-bracket counts.
def check_star(s):
    lo = hi = 0
    for c in s:
        lo += 1 if c == "(" else -1
        hi += 1 if c != ")" else -1
        if hi < 0: return False
        lo = max(lo, 0)
    return lo == 0
print(check_star("(**)))"), check_star("((*)"), check_star("*)(*"), check_star("(*)("))
What is printed?
  1. A. False True True False
  2. B. True True False False
  3. C. True False True False
  4. D. True True True False

Correct answer: D. True True True False

hi treats every '*' as '(' (if even that goes negative, too many ')'); lo treats every '*' as ')' but never below 0. Balanceable iff lo can reach 0 at the end. "(**)))": both stars as '(' → ((( ))). "*)(*": first star '(' and last star ')' → True. "(*)(": the final '(' can never close → False. O(n), O(1) – a backtracking search over 3^k choices is exponential.

More Coding Interview Problems questions

Exams that ask this topic