Skip to main content
Back to problems
#209
Medium Algorithms

Minimum size subarray sum

Array Binary Search Sliding Window Prefix Sum
51.1% acceptance
Jan 12, 2026
14276
536
Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_sub_array_len(target: i32, nums: Vec<i32>) -> i32 {
    let mut left = 0;
    let mut sum = 0;
    let mut min_len = i32::MAX;
    
    for right in 0..nums.len() {
      sum += nums[right];
      while sum >= target {
        min_len = min_len.min((right - left + 1) as i32);
        sum -= nums[left];
        left += 1;
      }
    }
    
    if min_len == i32::MAX { 0 } else { min_len }
  }
}