Data Structures & AlgorithmsVery hardProduct company OA · Amazon/Microsoft-style OA
Array a = [4, -1, 2, -3, 5, -2, 1, 1, -4]. How many DISTINCT values appear among the sums of all non-empty contiguous subarrays?
- A. 15
- B. 12
- C. 45
- D. 10
Correct answer: B. 12
Compute all prefix sums P, then every subarray sum is P[j] - P[i] for i < j. Counting distinct values, not subarrays, needs a set over the differences; counting subarrays would give the total number of intervals, which is far larger.
More Coding Interview Problems questions
- Array a = [6, 1, 8, 3, 9, 4, 2, 7, 5] has distinct values. How many ordered pairs (i, j) with i != j satisfy a[i] - a[j] = 4?
- For a = [1, 2, 3, 4, 5, 6, 7, 8], how many contiguous subarrays have a sum that is a multiple of 5?
- Array a = [2, 1, 5, 2, 3, 1, 4] has only positive values. How many non-empty contiguous subarrays have sum at most 9?
- Sorted values [1, 4, 6, 9, 13, 14, 18, 22] must be split into the fewest contiguous groups so that in every group the largest value minus…
- Two multisets A = {7, 2, 9, 4, 5} and B = {3, 8, 1, 6, 10} are matched one-to-one, pairing each element of A with exactly one element of…
- How many permutations of (1, 2, 3, 4, 5) have every pair of adjacent entries differing by at least 2? Solve with a bitmask DP that…