Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find a subarray with a given sum (positive numbers)

Locate a contiguous subarray of positive integers that sums to a target using the sliding window technique.

Python practice17 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given a list of positive integers and a target sum, find any contiguous subarray (by indices) that sums exactly to the target. If such a subarray exists, return a tuple (start_index, end_index) with 0-based inclusive indices. If no such subarray exists, return None. Because all numbers are positive, you can use a sliding window approach for O(n) time.

Task

Return the (start_index, end_index) of any contiguous subarray whose sum equals the target, or None if none exists. Use O(n) time with a sliding window.

Examples

Subarray in middle

Input

find_subarray_with_sum([1, 2, 3, 7, 5], 12)

Output

(1, 3)

The subarray [2, 3, 7] (indices 1 to 3) sums to 12.

Input format

Two arguments: a list of positive integers and an integer target, e.g. ([1,2,3,7,5], 12).

Output format

Return a tuple (start_index, end_index) of 0-based inclusive indices, e.g. (1, 3), or None if not found.

Constraints

All numbers are positive. 0 <= len(arr) <= 10^5. 1 <= target <= 10^9. Use O(n) time, O(1) extra space.

Samples

Sample 1

Input

[1, 4, 20, 3, 10, 5], 33

Output

(2, 4)

20 + 3 + 10 = 33, indices 2 through 4.