1249. Ring Target Stretches

A ring of sensors reports one reading each, listed in nums in order around the ring, so the last sensor sits next to the first. A stretch is a start index from 0 to n - 1 plus a length from 1 to n, where n is the length of nums; it covers consecutive sensors going forward and wraps around the end of the array.

Return, as a long, how many stretches have a total exactly equal to k. Different (start, length) pairs count separately even when they cover the same sensors, so the full ring is counted once for each start index. Use prefix sums over the doubled array and a hash map holding only the currently allowed ends. The intended solution runs in O(n) time and O(n) space.

Example 1

Input:
nums = [5,-2,7,-3,4,-6,8], k = 9
Output:
2
Explanation:

Of all stretches around the ring, only the one of length 5 from index 4 and the one of length 5 from index 5 add up to 9, giving 2.

Example 2

Input:
nums = [6,-4,6,-4,6,-4], k = 2
Output:
6
Explanation:

The readings alternate 6 and -4, so every length 2 stretch sums to 2 from each of the 6 starts, and no other length reaches 2, giving 6.

Example 3

Input:
nums = [9,14,-5,3,21], k = 12
Output:
1
Explanation:

Only the stretch of length 3 starting at index 1 (14 - 5 + 3) sums to 12, so the answer is 1.

Constraints

  • 1 ≤ nums.length ≤ 105

  • -104 ≤ nums[i] ≤ 104

  • -109 ≤ k ≤ 109

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,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…