1270. Leftover Stretches

A warehouse logs the net change in stock after every shift in the integer array nums; a negative value means more items left than arrived. An auditor may pick any non-empty run of consecutive shifts and add its changes together. Items are packed into boxes of exactly k, so the leftover of a run is its total taken modulo k as a non-negative remainder in the range 0 to k-1. A total of -1 with k = 5 therefore leaves 4, not -1.

Return how many runs have a leftover equal to r, as a long. Runs at different positions are different even when their contents match. Totals can reach 2 * 10^14, so use 64-bit arithmetic. Compare prefix sums taken modulo k using a hash map of counts.

The intended solution runs in O(n) time and O(n) space.

Example 1

Input:
nums = [14,-9,23,-31,8,17], k = 7, r = 2
Output:
1
Explanation:

Only the single shift [23] (index 2) has a total of 23, and 23 mod 7 = 2. No other run leaves 2, so the answer is 1.

Example 2

Input:
nums = [-13,26,-39,52,-5,6,41], k = 9, r = 0
Output:
2
Explanation:

The runs over indexes 0..5 and 1..6 have totals 27 and 81, both multiples of 9, so each leaves 0 and the answer is 2.

Example 3

Input:
nums = [-17,4,-250,31,9], k = 6, r = 5
Output:
2
Explanation:

Indexes 0..1 total -13 and 0..4 total -223. Both have remainder 5 modulo 6 once negatives wrap upward, so the answer is 2.

Constraints

1 ≤ nums.length ≤ 2 * 105

-109 ≤ nums[i] ≤ 109

1 ≤ k ≤ 109

0 ≤ r < k

The answer needs a 64-bit integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…