1250. Two Target Pieces

You are given an array nums and a target k. A piece is a non-empty contiguous subarray whose sum equals k. Count the ordered pairs of pieces (A, B) in which A ends at an index strictly smaller than the index where B starts, so the two pieces never overlap and A comes first. Pieces with different index ranges count separately even when their values match.

Return the count modulo 1000000007 as an integer. With prefix-sum hash maps, work out how many pieces end at each index and how many start at each index, then combine them using a running total of the ends. The intended solution runs in O(n) time and O(n) space, where n is the length of nums.

Example 1

Input:
nums = [1,1,1,1], k = 2
Output:
1
Explanation:

The only two non-overlapping pieces with sum 2 are the indices 0 to 1 followed by the indices 2 to 3.

Example 2

Input:
nums = [0,0,0], k = 0
Output:
5
Explanation:

The five ordered choices are index 0 before index 1, index 0 before index 2, index 1 before index 2, index 0 before the range 1 to 2, and the range 0 to 1 before index 2.

Example 3

Input:
nums = [1,2], k = 5
Output:
0
Explanation:

No subarray sums to 5, so there are no pieces and the answer is 0.

Constraints

  • 2 ≤ nums.length ≤ 105

  • -104 ≤ nums[i] ≤ 104

  • -109 ≤ k ≤ 109

  • the answer is taken modulo 1000000007

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…