Data Structures & AlgorithmsVery hardCodeforces Div2 D · two pointers
Problem: For the shortest subarray with sum at least S in an array of positive integers, a two-pointer sweep is used: extend the right end, then shrink the left end while the sum stays at least S. Why is this correct?
- A. Negative values make the window sum shrink, so the left pointer only moves forward
- B. The answer is always the whole array, so the sweep just checks it
- C. Positive values make the window sum monotone in each pointer move, so no valid answer is skipped
- D. Prefix sums are sorted, so binary search replaces the sweep
Correct answer: C. Positive values make the window sum monotone in each pointer move, so no valid answer is skipped
With positive values, growing the window never decreases its sum and shrinking never increases it, so the minimal valid left end can only advance. The argument fails for negative values, which is why a deque on prefix sums is needed there.
More Coding Interview Problems questions
- Problem: Weighted interval scheduling (each job has a start, finish and profit; choose a set of non-overlapping jobs to maximise profit)…
- Problem: What does the following print? It returns the next greater element of each position in a circular array (search continues from…
- Problem: How many cells of a 3 x 3 grid are at exactly 2 steps (4-directional moves, no obstacles) from the top-left cell? Run the BFS…
- Problem: How many ordered pairs (a, b) with 1 <= a, b <= 6 have gcd(a, b) = 1? python from math import gcd print(sum(1 for a in range(1…
- Problem: What does the following print? python print(sum(bin(i).count('1') for i in range(1, 16)))
- 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]?