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.
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
// 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;
} def unique_letter_string(s):
# each occurrence is unique in (i - previous) * (next - i) substrings
pos = {}
for i, c in enumerate(s):
pos.setdefault(c, [-1]).append(i)
total = 0
for idx in pos.values():
idx.append(len(s))
for k in range(1, len(idx) - 1):
total += (idx[k] - idx[k - 1]) * (idx[k + 1] - idx[k])
return total // sum over all substrings of the number of characters that appear once in them
int uniqueLetterString(string s) {
unordered_map<char, vector<int>> pos;
for (int i = 0; i < (int)s.size(); i++) pos[s[i]].push_back(i);
long long total = 0;
for (auto& [c, idx] : pos) {
idx.insert(idx.begin(), -1);
idx.push_back(s.size());
for (size_t k = 1; k + 1 < idx.size(); k++) // unique in (i - prev) * (next - i)
total += (long long)(idx[k] - idx[k - 1]) * (idx[k + 1] - idx[k]);
}
return (int)total;
} // sum over all substrings of the number of characters that appear once in them
function uniqueLetterString(s) {
const pos = new Map();
for (let i = 0; i < s.length; i++) {
if (!pos.has(s[i])) pos.set(s[i], [-1]);
pos.get(s[i]).push(i);
}
let total = 0;
for (const idx of pos.values()) {
idx.push(s.length);
for (let k = 1; k < idx.length - 1; k++) // unique in (i - prev) * (next - i)
total += (idx[k] - idx[k - 1]) * (idx[k + 1] - idx[k]);
}
return total;
} The variations
-
1Count what each element adds
For each position, count the substrings where it matters: choices for the left end × choices for the right end.
-
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³¹.
Lesson done
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.