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

Önek Toplam

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 / 8
2
1
3
4

pref = [0, ?, ?, ?, ?]

Build prefix with pref[0] = 0.

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.

Subarray Sum Equals K

Problem (restated)

Given an array of integers and an integer k, return the total number of continuous subarrays whose sum equals k.

Intuition

Prefix sums: count how often (pref - k) has occurred. Each such earlier prefix forms a valid subarray ending here.

Approaches

Prefix sum + hash map

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

Idea. count[0]=1. Walk array updating pref; ans += count[pref-k]; count[pref]++.

Walkthrough. nums=[1,1,1], k=2 → subarrays [1,1] twice → answer 2.

Trade-offs. Handles negatives (sliding window does not). Must seed count[0]=1.

Solution
export function subarraySum(nums: number[], k: number): number {
  const count = new Map<number, number>([[0, 1]]);
  let pref = 0, ans = 0;
  for (const x of nums) {
    pref += x;
    ans += count.get(pref - k) ?? 0;
    count.set(pref, (count.get(pref) ?? 0) + 1);
  }
  return ans;
}
export function subarraySum(nums: number[], k: number): number {
  const count = new Map<number, number>([[0, 1]]);
  let pref = 0, ans = 0;
  for (const x of nums) {
    pref += x;
    ans += count.get(pref - k) ?? 0;
    count.set(pref, (count.get(pref) ?? 0) + 1);
  }
  return ans;
}

Template connection

Prefix sum + hashmap from the Prefix Sum template.

Reflection