Data Structures & AlgorithmsHardCodeforces Div 2 C · ICPC regional
Array a = [1, -1, 2, 3, -2, 4, -3, 1]. How many contiguous non-empty subarrays have sum exactly 3? Solve it with running prefix sums and a hash map counting how often each prefix value has been seen.
- A. 5
- B. 4
- C. 6
- D. 3
Correct answer: A. 5
Count pairs of prefixes (i < j) with prefix[j] - prefix[i] = 3. Leaving out the empty prefix 0 from the map drops every subarray that starts at index 0, giving 4 instead of 5.
More Coding Interview Problems questions
- For a = [3, 4, -7, 2, -2, 5, -5, 1, 6], what is the length of the longest contiguous subarray whose elements sum to 0?
- Array a = [-2, 3, -4, 6, -1, 2]. How many non-empty subarrays have a sum divisible by 5? Count prefix sums by their remainder, normalised…
- In the binary string s = "1100110100", count the non-empty substrings that contain exactly as many 0s as 1s.
- Array a = [2, 7, -3, 5, 11, 4, 9, -1, 6]. How many index pairs (i, j) with i < j have a[i] + a[j] = 10?
- Array a = [2, 1, -1, 4, -2, 3, 0, 1, 1, 0, 2]. How many indices i have the sum of the elements strictly left of i equal to the sum of the…
- Array a = [3, 1, 2, 6, 4, 5, 9]. How many index pairs (i < j) satisfy a[i] mod 3 = a[j] mod 3?