AlgoTales · Roadmap

Subarray-sum problems

Intermediate · 11 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

These problems ask how many stretches of consecutive items add up to a particular value. The trick is to keep a running total and a map of how often each total was seen, so each new item answers the question with one lookup.

Practical use cases

  • Web app: Auditing payments for a fixed amount. A finance admin wants every run of consecutive transactions that totals exactly Rs 10,000, for a reconciliation. The code walks through the ledger once, keeping running totals in a map, and counts matches as it goes. A ledger of 100,000 lines is checked in a moment, not a night.
  • Web app: Streak counter in a fitness app. A fitness app marks days as +1 for goal met and -1 for missed. To count stretches where goals and misses balanced exactly, it uses running totals and a map of how often each total appeared. The monthly summary page loads without long calculation.
  • System: Sensor streams and anomaly checks. A factory monitor reads a stream of changes in temperature. It looks for windows where the total change hit a suspicious value, remembering earlier totals in a map. Each new reading needs only one lookup, so the monitor keeps up with the stream and raises an alert as soon as it sees a match.

The story: Counting the Lucky Stretches

Zoya ran the school's annual fundraising stall. After each hour she wrote how much money came in: 3, 4, 7, 2, -3 (a refund!), 1, 4, 2. The principal announced a game: "Any stretch of consecutive hours that earned exactly 7 rupees in total is a lucky stretch. How many lucky stretches are there?"

Zoya's first plan was to start at each hour and keep adding forward until the total passed 7, then start again from the next hour. But with the refund making the total go down again, she could not stop early: she had to check every ending. That is a lot of adding when the day has hundreds of hours.

Aarav remembered the passbook trick. "Keep a running total. A lucky stretch ending now exists for each earlier moment when the running total was exactly (now minus 7). If that earlier total showed up three times, there are three lucky stretches ending right now!" So the map stores how many times every running total has appeared. A single pass gave the answer, and the principal gave the stall a prize. This counting version, together with variations (sum zero, equal 0s and 1s, divisible by k), forms the family of subarray-sum problems.

How to spot this problem, and where you need it

You must count or find all stretches of back-to-back values whose total equals a target, and checking every possible stretch takes far too long on real data.

Signs you need it

  • The problem asks for "number of subarrays with sum k" or "longest subarray with sum k", especially when values can be negative.
  • Your first solution uses two nested loops that add up every possible stretch, and it times out on large input.
  • Sliding a window does not work because values can be negative or zero, so a window cannot just grow and shrink.

Where to use it in a project

  • Reconciliation or audit tools that match runs of entries to a fixed total.
  • Analytics on time series where you count periods with a specific net change.

The solution

Start with a map saying "total 0 has been seen once". Walk through the items keeping a running total. At each item, look up running total minus target in the map; the number you find is how many stretches end here with the target sum. Add that to your answer, then record the current running total in the map. One pass, one lookup per item.

Payoff: Before: about 5 billion additions for 100,000 entries. After: 100,000 lookups, done in well under a second.

Explain it like I am 8

Walk along a ladder and call out your height at every rung. To find all the climbs that gained exactly 7 rungs, whenever you reach a new rung, ask your friend with the notebook: "How many times were we ever at a height 7 lower than this?" That number is how many 7-climbs end here.

How it works, step by step

  1. Keep a running total pre and a map seen counting how often each total has occurred. Start with seen[0] = 1.
  2. For each number, add it to pre.
  3. Add seen[pre - k] (or 0 if missing) to your answer: each earlier equal total is the start of one valid stretch.
  4. Then record the current total: seen[pre] += 1. (Record after counting, so an empty stretch is never counted.)
  5. The same pattern solves other problems: sum zero (k = 0), or equal numbers of 0s and 1s by treating 0 as -1.

The code in four languages

PHP

<?php
// 1) How many stretches add up to exactly $k? (negatives allowed)
function countSubarraysWithSum(array $nums, int $k): int {
    $seen = [0 => 1];            // running total => how many times it has occurred
    $pre = 0;
    $count = 0;
    foreach ($nums as $x) {
        $pre += $x;
        $count += $seen[$pre - $k] ?? 0;          // every earlier matching total starts a stretch
        $seen[$pre] = ($seen[$pre] ?? 0) + 1;     // record AFTER counting
    }
    return $count;
}

// 2) Longest stretch with equal numbers of 0s and 1s (treat 0 as -1, find sum 0)
function longestBalanced(array $bits): int {
    $first = [0 => -1];
    $pre = 0;
    $best = 0;
    foreach ($bits as $i => $b) {
        $pre += $b === 1 ? 1 : -1;
        if (array_key_exists($pre, $first)) $best = max($best, $i - $first[$pre]);
        else $first[$pre] = $i;
    }
    return $best;
}

echo countSubarraysWithSum([3, 4, 7, 2, -3, 1, 4, 2], 7) . "\n";   // 4
echo longestBalanced([0, 1, 0, 0, 1, 1, 0]) . "\n";                // 6

JavaScript

// 1) How many stretches add up to exactly k? (negatives allowed)
function countSubarraysWithSum(nums, k) {
  const seen = new Map([[0, 1]]);   // running total => how many times it has occurred
  let pre = 0, count = 0;
  for (const x of nums) {
    pre += x;
    count += seen.get(pre - k) ?? 0;              // every earlier matching total starts a stretch
    seen.set(pre, (seen.get(pre) ?? 0) + 1);      // record AFTER counting
  }
  return count;
}

// 2) Longest stretch with equal numbers of 0s and 1s (treat 0 as -1, find sum 0)
function longestBalanced(bits) {
  const first = new Map([[0, -1]]);
  let pre = 0, best = 0;
  bits.forEach((b, i) => {
    pre += b === 1 ? 1 : -1;
    if (first.has(pre)) best = Math.max(best, i - first.get(pre));
    else first.set(pre, i);
  });
  return best;
}

console.log(countSubarraysWithSum([3, 4, 7, 2, -3, 1, 4, 2], 7));   // 4
console.log(longestBalanced([0, 1, 0, 0, 1, 1, 0]));                // 6

Java

import java.util.*;

public class Main {
    // 1) How many stretches add up to exactly k? (negatives allowed)
    static int countSubarraysWithSum(int[] nums, int k) {
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, 1);                  // running total => how many times it has occurred
        int pre = 0, count = 0;
        for (int x : nums) {
            pre += x;
            count += seen.getOrDefault(pre - k, 0);           // every earlier matching total starts a stretch
            seen.merge(pre, 1, Integer::sum);                 // record AFTER counting
        }
        return count;
    }

    // 2) Longest stretch with equal numbers of 0s and 1s (treat 0 as -1, find sum 0)
    static int longestBalanced(int[] bits) {
        Map<Integer, Integer> first = new HashMap<>();
        first.put(0, -1);
        int pre = 0, best = 0;
        for (int i = 0; i < bits.length; i++) {
            pre += bits[i] == 1 ? 1 : -1;
            if (first.containsKey(pre)) best = Math.max(best, i - first.get(pre));
            else first.put(pre, i);
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(countSubarraysWithSum(new int[]{3, 4, 7, 2, -3, 1, 4, 2}, 7));   // 4
        System.out.println(longestBalanced(new int[]{0, 1, 0, 0, 1, 1, 0}));                // 6
    }
}

Go

package main

import "fmt"

// countSubarraysWithSum: how many stretches add up to exactly k? (negatives allowed)
func countSubarraysWithSum(nums []int, k int) int {
	seen := map[int]int{0: 1} // running total => how many times it has occurred
	pre, count := 0, 0
	for _, x := range nums {
		pre += x
		count += seen[pre-k] // every earlier matching total starts a stretch
		seen[pre]++          // record AFTER counting
	}
	return count
}

// longestBalanced: longest stretch with equal numbers of 0s and 1s (treat 0 as -1, find sum 0)
func longestBalanced(bits []int) int {
	first := map[int]int{0: -1}
	pre, best := 0, 0
	for i, b := range bits {
		if b == 1 {
			pre++
		} else {
			pre--
		}
		if j, ok := first[pre]; ok {
			best = max(best, i-j)
		} else {
			first[pre] = i
		}
	}
	return best
}

func main() {
	fmt.Println(countSubarraysWithSum([]int{3, 4, 7, 2, -3, 1, 4, 2}, 7)) // 4
	fmt.Println(longestBalanced([]int{0, 1, 0, 0, 1, 1, 0}))              // 6
}

Time: O(n) · Extra space: O(n). A single pass with constant-time map updates; the map stores at most n + 1 different running totals.

Watch out for

  • Storing only whether a total was seen instead of how many times, which undercounts when the same total repeats.
  • Recording the current total before counting, which can wrongly count an empty stretch when k = 0.
  • Forgetting seen[0] = 1, which misses stretches that begin at the first number.

Quick check

  1. Running total is 9, k is 7, and total 2 has been seen 3 times before. How many stretches end here?
    • 1
    • 2
    • 3
  2. How can you turn "equal 0s and 1s" into a sum problem?
    • Sort the bits
    • Treat each 0 as -1 and look for sum 0
    • Count only the 1s
  3. Time complexity of the one-pass counting method?
    • O(n)
    • O(n²)
    • O(n log n)