İçeriğe atla
ΣDSA Patterns
Menü
Dil

Kayar Pencere

Rehber 3 / 6 · Yol 3 / 6

Interactive

Zihinsel model

Bu problem için animasyonlu çözüm. Adımları kaydır veya boşlukla duraklat; değişmezi yüksek sesle yeniden anlat.

Adım 1 / 9
a
b
c
a
b
b

best = 0

Start with an empty window. Invariant: all characters unique.

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

Minimum Size Subarray Sum

Problem (restated)

Given a positive integer array nums and a positive integer target, return the minimal length of a contiguous subarray whose sum is ≥ target. Return 0 if no such subarray exists.

Intuition

Because all values are positive, expanding the right end only increases the sum and shrinking the left only decreases it. classic variable window.

Approaches

Sliding window

Tested only
Time O(n)Space O(1)

Idea. Grow right while sum < target. When sum ≥ target, shrink left as far as possible and track min length.

Walkthrough. nums=[2,3,1,2,4,3], target=7. Window grows to [2,3,1,2] sum=8 → length 4. Shrink to [3,1,2] then [1,2,4]… eventually [4,3] length 2.

Trade-offs. Optimal linear scan. Binary search on prefix sums is O(n log n) and only needed if negatives appear (they do not here).

Solution
export function minSubArrayLen(target: number, nums: number[]): number {
  let left = 0, sum = 0, best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    sum += nums[right]!;
    while (sum >= target) {
      best = Math.min(best, right - left + 1);
      sum -= nums[left++]!;
    }
  }
  return best === Infinity ? 0 : best;
}
export function minSubArrayLen(target: number, nums: number[]): number {
  let left = 0, sum = 0, best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    sum += nums[right]!;
    while (sum >= target) {
      best = Math.min(best, right - left + 1);
      sum -= nums[left++]!;
    }
  }
  return best === Infinity ? 0 : best;
}

Reflection