Data Structures & AlgorithmsVery hardProduct company OA
What is the sum of min(subarray) over all contiguous subarrays of [2, 5, 1, 4, 3]? (A monotonic stack counts, for each element, how many subarrays it is the minimum of.)
- A. 15
- B. 28
- C. 25
- D. 31
Correct answer: B. 28
a[i] is the minimum of (choices of left end) × (choices of right end) subarrays, extending until a smaller element. 2: 1 × 2 → 2·2 = 4; 5: 1 × 1 → 5; 1: 3 × 3 → 9; 4: 1 × 1 (3 to its right is smaller) → 4; 3: 2 × 1 (it can extend left over 4) → 6. Total 4 + 5 + 9 + 4 + 6 = 28. Summing the elements once (15) ignores that each element is the minimum of several subarrays.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the length of the longest substring of ')()())(()())' that is a valid (balanced) parentheses string?
- The stock span of day i is the number of consecutive days ending at day i whose price is ≤ the price on day i. For prices [31, 27, 14, 21…
- What is the minimum number of swaps (of any two elements) needed to sort the permutation [4, 3, 1, 2, 6, 5] into ascending order?
- A stack-based decoder expands k[s] into s repeated k times (nesting allowed). What does '2[x3[y]z]q' decode to?
- Adjacent equal pairs are removed repeatedly with a stack until none remain. What is left of 'pqqprrsttsx'?
- An array is split into the MAXIMUM number of contiguous chunks such that sorting each chunk separately and concatenating them gives the…