Subarray with Given Sum (non-negative numbers)
Problem Statement
You are given an array arr of non-negative integers (zeros are allowed) and a number target.
Find a contiguous subarray whose sum is exactly target. Return its start and end positions as 1-based indices, [start, end]. If several subarrays work, return the first one (the one that starts furthest left). If none works, return [-1].
In this walkthrough the subarray must have at least one element. So for target = 0, the answer is the position of the first 0 in the array, or [-1] if there is no zero.
An integer array arr of non-negative numbers, and an integer target.
A list [start, end] with 1-based positions, or [-1] if no subarray sums to target.
Positions 2 to 4 hold 2 + 3 + 7 = 12. ([7, 5] also adds to 12, but it starts later.)
1 + 2 + 3 + 4 + 5 = 15, starting at the very first position.
Every element is bigger than 2, so no subarray can add up to exactly 2.
The subarray must not be empty. The first one with sum 0 is the single 0 at position 2.
- • 1 ≤ arr.length ≤ 10^6
- • 0 ≤ arr[i] ≤ 10^3
- • 0 ≤ target ≤ 10^9
- • Sums can reach 10^9 — keep them in a 64-bit type to be safe.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For every start, extend the end and compare the running sum with target
A subarray sums to target when two running totals differ by target
Grow right; while sum > target, drop from the left; stop when sum == target
Go through starts from left to right. For each start, extend the end one step at a time, keeping a running sum. The first time the sum equals target, return that range. Because we try starts in order, the first match has the smallest start.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.