0PricingLogin
Competitive Programming Academy · Lesson

Count Subarrays with a Target Sum

Combine prefix sums with a hash map.

A Harder Question

Now the twist: count how many subarrays add up to a target k. Checking every pair is slow, but prefix sums plus a hash map crack it. 🎯

Reframe with Prefixes

A subarray sum equals prefix[r + 1] minus prefix[l]. So a sum of k means two prefix values differ by exactly k.

All lessons in this course

  1. Build a Prefix Sum Array
  2. Sum Any Range with Subtraction
  3. Count Subarrays with a Target Sum
  4. Difference Arrays for Range Updates
← Back to Competitive Programming Academy