Longest Subarray Sum

Longest Subarray Sum

Given a slice of positive integers and a target, return the length of the longest contiguous subarray that sums to exactly target. Return 0 if none exists.

longestSubarraySum(nums, target)

Input format: nums | target.

Examples

[1, 1, 1, 1], target=2   // → 2
[3, 1, 1, 1, 2], target=3 // → 3   (1+1+1)
[5, 6], target=4          // → 0

Walkthrough

Thinking it through

A close cousin of finding any window that sums to the target, except now you need the longest one. Brute force — check every (start, end) pair, record the widest one summing to target — is O(n²), wasting effort re-summing overlapping ranges.

Leaning on positivity again

Since every number is positive, the same monotonic guarantee applies: extending on the right can only increase the sum, trimming from the left can only decrease it. A two-pointer variable window is safe — the effect of each move is always predictable.

Why you don't need to shrink once the sum matches

Here's the subtlety separating "find one" from "find the longest." Earlier, once the sum equals target you stop. Here, a wider window found later might also match and beat your current best. So keep expanding, and every time the sum equals target, compare that window's width to the best seen so far.

The specific shrink condition

The window only shrinks when its sum grows past the target. Positivity makes "sum too big" an unambiguous signal to trim from the left, one element at a time, until it's no longer over. You never shrink just because the sum is below target — that's fine, keep expanding.

Building the approach

  1. Expand by advancing right, adding each new element to a running sum.
  2. While the sum exceeds target, shrink from the left until it's at or below target.
  3. Whenever the sum equals target, compute the width (right - left + 1) and update the best if wider.
  4. Continue until right reaches the end; the best length is the answer, or 0 if none matched.

Why this is efficient

Each element is added once and removed at most once, so both pointers only move forward — roughly 2n total movements instead of O(n²). The only change from "find any window" is tracking the best instead of stopping at the first hit.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.