Data Structures & AlgorithmsHardProduct Company SDE · stack round
Problem: Sum the minimum of every non-empty subarray of [3, 1, 2, 4] by brute force.
Problem: Sum the minimum of every non-empty subarray of [3, 1, 2, 4] by brute force.
a = [3, 1, 2, 4] print(sum(min(a[i:j + 1]) for i in range(len(a)) for j in range(i, len(a))))What is printed?
- A. 17
- B. 15
- C. 19
- D. 21
Correct answer: A. 17
The ten subarrays have minima 3,1,1,1,1,1,1,2,2,4 which sum to 17. A monotone-stack solution computes the same total in O(n) by counting how many subarrays each element minimises.
More Coding Interview Problems questions
- Problem: Count inversions in [2, 4, 1, 3, 5] with a Fenwick tree over the values. python def inv(a): n = max(a) t = [0] (n + 1) def…
- Problem: Run Bellman-Ford style negative-cycle detection (all distances start at 0, V - 1 rounds, then one extra check) on 3 vertices with…
- Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from…
- Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and…
- Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices…
- Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'. python def lcssub(a, b): best = 0 dp =…