Fundamentals/Prefix Sum
← PrevNext →
Given an integer array arr and an integer target, return a contiguous subarray whose elements sum to target as the half-open range [start, end), where start is inclusive and end is exclusive. If no such subarray exists, return an empty array.
Input
arr: array of integers (may include negatives)
target: integer sum to find
Output
A two-element array [start, end) describing the subarray, or [] if none exists.
Examples
Example 1
Inputarr = [1, -20, -3, 30, 5, 4], target = 7
Output[1, 4]
Explanation: arr[1..4) = [-20, -3, 30] sums to 7.
Example 2
Inputarr = [1, 2, 3, 4, 5], target = "hello"
Output[]
Constraints
1 <= arr.length <= 10^5
Return the first matching subarray encountered while scanning left-to-right.