Skip to content

Subarray Sum To Target

EasyPython 3Two pointersArrays

You are given an array arr of positive integers and a positive integer target. Return the pair of indices (start, end), inclusive, of a contiguous subarray whose values sum exactly to target. If several subarrays qualify, return the one with the smallest starting index. If none exists, return None.

Constraints:
  - 1 <= len(arr) <= 10^5
  - 1 <= arr[i] <= 10^9
  - 1 <= target <= 10^14
Examples:
  arr = [1, 5, 10, 3], target = 18 -> (1, 3)   (5 + 10 + 3)
  arr = [1, 2, 3, 4],  target = 9  -> (1, 3)   (2 + 3 + 4)
  arr = [5],           target = 5  -> (0, 0)
  arr = [1, 2, 3],     target = 7  -> None      (whole array sums to 6)

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…