Data Structures & AlgorithmsVery hardProduct company OA · Amazon/Microsoft-style OA
Array a = [5, -3, 2, 4, -6, 1, 3, -2]. How many non-empty contiguous subarrays have a sum in the closed range [0, 4]?
- A. 20
- B. 18
- C. 22
- D. 17
Correct answer: A. 20
Prefix sums turn the question into counting pairs p[i] < p[j] with p[j] - 4 <= p[i] <= p[j] - 0. Keeping the prefixes in a sorted structure answers each query in logarithmic time, and the count of pairs is the answer.
More Coding Interview Problems questions
- For the string s = "aabbabbaab", find the length of the longest substring with exactly as many letter a as letter b.
- For the array a = [4, 1, 7, 2, 2, 5, 3, 6], how many contiguous non-empty subarrays have XOR equal to 0? Use prefix XOR values.
- Array a = [3, 1, 4, 1, 5, 9, 2, 6]. How many subarrays of length exactly 3 have an even sum?
- Array a = [2, 4, 6, 1, 3, 5, 8, 7]. How many contiguous subarrays of length at least 2 have a sum divisible by 4?
- From the sorted side lengths [4, 6, 7, 9, 10, 13, 15], how many different triples (choosing distinct positions) can form a non-degenerate…
- Sorted arrays A = [1, 7, 12, 20, 31] and B = [3, 9, 15, 25, 40]. What is the smallest value of |x - y| over x in A and y in B?