Data Structures & AlgorithmsVery hardProduct Company SDE · stack round
Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code.
Problem: What is the length of the longest valid (well-formed) parenthesis substring of ')()())'? Run the stack code.
s = ')()())'
st = [-1]
best = 0
for i, c in enumerate(s):
if c == '(':
st.append(i)
else:
st.pop()
if not st:
st.append(i)
else:
best = max(best, i - st[-1])
print(best)What is printed?- A. 2
- B. 4
- C. 6
- D. 0
Correct answer: B. 4
The substring '()()' at indices 1 to 4 is well-formed and has length 4. The stack stores the index before each valid block, so the distance gives its length.
More Coding Interview Problems questions
- Problem: What is the value of the reverse Polish expression '2 1 + 3 '? Run the stack code. python tokens = '2 1 + 3 '.split() st = [] for…
- Problem: What is the maximum matching size in the bipartite graph with left vertices {0,1,2}, right vertices {0,1,2} and edges (0,0)…
- Problem: How many integers x in [1, 100] satisfy x^2 ≡ 1 (mod 8)? Run the code. python print(sum(1 for x in range(1, 101) if (x x) % 8 ==…
- Problem: What is the smallest positive integer x with x ≡ 1 (mod 4) and x ≡ 2 (mod 5)? Run the code. python print(next(x for x in range(1…
- Problem: How many integers in [1, 100] have non-decreasing decimal digits (for example 1245 or 3399, but 2 digits only here)? Run the…
- Problem: What is the spiral (clockwise from the top-left) traversal of the matrix [[1,2,3],[4,5,6],[7,8,9]]? Print the list produced by…