Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the longest valid (well-formed) parentheses substring.
Problem: Find the length of the longest valid (well-formed) parentheses substring.
def longest_valid(s):
st, best = [-1], 0
for i, ch in enumerate(s):
if ch == '(':
st.append(i)
else:
st.pop()
if not st: st.append(i)
else: best = max(best, i - st[-1])
return best
print(longest_valid(")()())"), longest_valid("(()(()"), longest_valid("()(())"))What is printed?- A. 4 2 6
- B. 4 4 6
- C. 4 2 4
- D. 2 2 6
Correct answer: A. 4 2 6
The stack bottom holds the index just before the current valid run. ")()())" → "()()" = 4. In "(()(()" the unmatched '(' at index 3 splits the string, so the best is 2, not 4. "()(())" is entirely valid → 6. O(n).
More Coding Interview Problems questions
- Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS. java static int provinces(int[][] m) {…
- Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none). python def judge(n, trust): score = [0] (n + 1)…
- Problem: Find the cheapest network latency to reach all nodes from node k (network delay = max shortest distance). python import heapq def…
- Problem: Clone check – count how many nodes a BFS reaches from node 0 in a directed graph that contains a cycle. python from collections…
- Problem: Print a matrix in spiral order (clockwise from the top-left). cpp vector<int> spiral(vector<vector<int>>& m) { vector<int> out…
- Problem: Rotate an n × n image 90° clockwise in place. python def rotate(m): n = len(m) for i in range(n): for j in range(i + 1, n)…