Arrays & Hashing · Pattern 20 of 26

The contribution technique

Instead of looping over every substring, ask how many substrings each element contributes to. A character is unique in (i − prev) × (next − i) substrings.

2 variations · 2 problems

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • A sum or count over all substrings or subarrays
  • n up to 10⁵, so O(n²) substrings is too slow

The template

Contribution Technique
// sum over all substrings of the number of characters that appear once in them
int uniqueLetterString(String s) {
    int n = s.length();
    int[] prev = new int[26], prev2 = new int[26];   // last two positions of each letter
    Arrays.fill(prev, -1); Arrays.fill(prev2, -1);
    long total = 0;
    for (int i = 0; i <= n; i++) {
        // when letter c appears at i, its previous occurrence prev[c] is unique
        // in (prev[c] - prev2[c]) * (i - prev[c]) substrings
        for (int c = 0; c < 26; c++) {
            if (i < n && s.charAt(i) - 'A' != c) continue;
            if (prev[c] >= 0) total += (long) (prev[c] - prev2[c]) * (i - prev[c]);
            prev2[c] = prev[c]; prev[c] = i;
        }
    }
    return (int) total;
}

The variations

  1. 1Count what each element adds

    For each position, count the substrings where it matters: choices for the left end × choices for the right end.

  2. 2Count over runs

    Group the string into runs of equal characters. Two neighbouring runs of lengths a and b contribute min(a, b) substrings.

Mistakes to avoid

  • Off-by-one in the boundaries: use −1 before the first occurrence and n after the last.
  • Overflow: the total over all substrings can pass 2³¹.
Next: KMP: string matching in O(n + m) →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.