Data Structures & AlgorithmsHardCodeforces Div2 B-D · ICPC regional
An array of 200000 integers may contain negative values, and you must count its contiguous subarrays whose sum equals K in near-linear time. Which technique fits, and why?
- A. Prefix sums with a hashmap counting earlier equal prefixes, because two-pointer windows need monotone sums and negatives break that
- B. Sliding window with two pointers, because every sum window can be shrunk greedily
- C. Binary search on the answer, because the sum is monotone in the subarray length
- D. Monotonic stack, because each element is the maximum of its subarray
Correct answer: A. Prefix sums with a hashmap counting earlier equal prefixes, because two-pointer windows need monotone sums and negatives break that
Negative values make the window sum non-monotone in the right end, so the usual shrink rule fails. Prefix sums turn each subarray into a difference of two prefixes, which a hashmap counts in O(n).
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
- For a string of length 10^6 and a pattern of 20 letters, you need the shortest substring containing every pattern letter with…
- Given an array of 10^6 values and window size k, you need the maximum over all windows of the window minimum. What is the most suitable…
- How many contiguous subarrays of [1, 2, 1, 3, 2, 2, 1] contain at most two distinct values?
- You may increase any element of [2, 5, 3, 9] by 1 per operation, and you want all elements equal. What is the minimum number of operations?
- In the binary row [1, 1, 0, 1, 1, 1] treated as a histogram of height 1, what is the largest rectangle area?
- What is the length of the shortest contiguous subarray of [5, 1, 4, 3, 2, 6, 7] whose sum is at least 15?