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?- A. False True True False
- B. True True False False
- C. True False True False
- 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
- Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag…
- Problem: Tower of Hanoi: move n disks from peg A to peg C using B, recording every move. python moves = [] def hanoi(n, a, b, c): if n ==…
- Problem: Mirror a binary tree (swap every node's children) and print its inorder traversal. Trees are built from a level-order list by…
- Problem: Generate all distinct subsets of a multiset of coupon values (skip equal values at the same recursion depth). python def…
- Problem: Produce the 3-bit Gray code sequence (consecutive codes differ in exactly one bit) with the formula g = i XOR (i >> 1). python…
- Problem: Trace the output of a recursive function that prints before and after its recursive call. python def walk(n): if n == 0: return…