CP: Subarrays that add up to k

Count how many stretches of consecutive numbers in an array add up to exactly k. Numbers may be negative, so two pointers will not work.

What to build

Build the prefix sums pre[0..n]. A stretch a[i..j-1] has sum k when pre[j] - pre[i] = k. Put every {pre value, position} pair in a sorted vector; then for each j, count the pairs with value pre[j] - k and a position smaller than j using two lower_bound calls.

Requirements

  • Count stretches of length at least 1
  • Include the empty prefix pre[0] = 0
  • Run in O(n log n)

Input

The first line has n and k. The second line has n whole numbers.

Output

The number of stretches a[i..j] whose sum is k.

Constraints

1 ≤ n ≤ 100,000. Values and k are between -10⁹ and 10⁹. The answer fits in long long.

Example

Input:

5 5
1 2 3 -1 4

Output:

2

Why it works

For each j, the valid starts i are the earlier positions whose prefix sum equals pre[j] - k. In a vector of {value, position} pairs sorted as pairs, those entries form one block: from {target, -1} up to {target, j}. The difference of two lower_bound positions is the size of that block. Starting from position 0 counts the stretches that begin at the first number.

Examples

Example 1 · Input
5 5
1 2 3 -1 4
Expected output
2
Example 2 · Input
4 0
0 0 0 0
Expected output
10

Hints

Hint 1

vector<pair<long long, int>> v; with v.push_back({pre[i], i}) for i = 0..n, then sort(v.begin(), v.end()).

Hint 2

For each j: target = pre[j] - k; count += lower_bound(v.begin(), v.end(), make_pair(target, j)) - lower_bound(v.begin(), v.end(), make_pair(target, -1)).

Hint 3

Pairs compare by value first, then position, so the block with value target and position below j sits between those two bounds.

Solution

Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    long long k;
    cin >> n >> k;
    vector<long long> pre(n + 1, 0);
    for (int i = 0; i < n; i++) {
        long long x;
        cin >> x;
        pre[i + 1] = pre[i] + x;
    }
    vector<pair<long long, int> > v;
    for (int i = 0; i <= n; i++) v.push_back(make_pair(pre[i], i));
    sort(v.begin(), v.end());
    long long answer = 0;
    for (int j = 1; j <= n; j++) {
        long long target = pre[j] - k;
        int hi = lower_bound(v.begin(), v.end(), make_pair(target, j)) - v.begin();
        int lo = lower_bound(v.begin(), v.end(), make_pair(target, -1)) - v.begin();
        answer += hi - lo;
    }
    cout << answer << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Prefix sums →