Contribution Technique

Intermediate · 30 min read · Problem-Solving Patterns, Greedy & Special Topics

Sum over all subarrays, pairs, subsets or tree paths in O(n): count what each element adds, with bits, prefix sums, stacks, windows and trees.

Some problems ask you to add something up over every subarray, every pair, every subset, every substring or every path in a tree: "the sum of all subarray minimums", "the total Hamming distance between all pairs", "the sum of the widths of all subsequences".

It isn't a separate algorithm so much as a way of looking. It combines with almost every pattern you already know: plain counting, bit manipulation, sorting with prefix sums, previous/next occurrence, the monotonic stack, the sliding window and tree DFS.

The idea: swap the order of the two sums

Any "sum over all subarrays" is really a double sum: over every subarray, over the elements (or the one element) that make up its value. You may add a grid of numbers row by row or column by column; the total is the same. Brute force adds row by row (one subarray at a time).

Plain counting: the subarrays that contain index i

A subarray containing index i is fixed by two independent choices: where it starts (anywhere from 0 to i, so i + 1 choices) and where it ends (anywhere from i to n − 1, so n − i choices). Every start pairs with every end, so index i is in exactly (i + 1) × (n − i) subarrays.

With bit manipulation: one column at a time

XOR, AND and OR work on each bit position independently: bit b of x ^ y depends only on bit b of x and bit b of y. So a sum over pairs or subsets can be split into 32 separate problems, one per column. In one column, only the count of 1s matters, not which numbers have them.

With sorting and prefix sums

|x − y| doesn't care about order, so you're free to sort. Once the array is sorted, the absolute value disappears: in every pair, the element on the right is the larger one. Then a[i] contributes

With the previous and next occurrence: strings

When the value of a substring depends on which letters it contains, a letter that appears twice in a substring must not be counted twice. Give the credit to one copy only.

With a monotonic stack: where is a[i] the minimum?

Sum of Subarray Minimums (907) is the classic. a[i] is the minimum of exactly the subarrays that contain i and stay between the nearest smaller value on each side.

With a sliding window: credit every subarray to its right end

Counting subarrays with a property (rather than adding values) uses the same idea with a different unit: the right end. If all values are positive, shrinking a valid subarray keeps it valid.

On trees: credit every path to the edges it uses

The distance between two nodes is the number of edges on their path. So the sum of distances over all pairs is the sum, over every edge, of how many paths cross it. Cut an edge and the tree falls into two parts: the subtree below it (size s) and the rest (n − s).

With counting subsets

The simplest counting fact of all: a given element is in exactly half of the 2ⁿ subsets, 2^(n − 1), because every subset without it pairs up with the same subset plus it. So the sum of all subset sums is (sum of the array) × 2^(n − 1), and Sum of All Subset XOR Totals used the same pairing argument per bit.

Choosing the unit

Practice ladder

Interview questions

  • What is the contribution technique, in one sentence?
  • Why is index i in exactly (i + 1) × (n − i) subarrays?
  • In Sum of Subarray Minimums, why is one boundary strict and the other not?
  • How do you get the total Hamming distance of all pairs in O(32n) instead of O(n²)?
  • Sum of all pairwise distances in a tree: how does contribution make it O(n)?

Further reading

Key takeaways

  • Turn "sum over all subarrays / pairs / subsets" around: sum, over each element, of (its value) × (how many of them it's in).
  • The count is nearly always (choices on the left) × (choices on the right): (i + 1)(n − i), (i − prev)(next − i), s × (n − s).
  • The unit can be an element, a bit column, a letter, a right end or a tree edge. Pick the one whose count is easy.
  • It combines with everything: bits (ones × zeros), sorting + prefix sums, last-seen arrays, monotonic stacks, sliding windows, tree DFS.
  • Watch ties (strict on one side only), overflow (long, and % MOD after each multiplication) and negative remainders.

Previous: Bit Manipulation · Next: Designing Data Structures