Files
usaco/solving/subarrays-distinct-element-sum-of-squares-ii/explain.md
T

19 KiB
Raw Blame History

Explained by claude-opus-5-5 on 19 October 2026.

Key observation

Appending nums[j] adds exactly 1 to the distinct count of every window starting after the previous occurrence of nums[j]. Since (d+1)^2 − d^2 = 2d + 1, the change in the sum of squares depends only on the plain sum of the old counts on that range.

Hint 1

Fix the right endpoint j and think about the distinct counts of all subarrays ending at j at once. How do they change when you move from j−1 to j?

Hint 2

When nums[j] arrives, only the windows that did not already contain that value gain a distinct element. Which left endpoints are those, in terms of the previous occurrence of nums[j]?

Hint 3

Write (d+1)^2 − d^2 = 2d + 1. Summed over a range, the change in the sum of squares only needs the plain sum of the d values on that range.

Hint 4

So you need a structure that supports range +1 and range sum. You can get this from two Fenwick trees over a difference array, using prefix(i) = (i+1)·Σdiff[t] − Σdiff[t]·t.

Approach

Why the obvious approaches fail

There are about n^2/2 subarrays, roughly 5·10^9 when n = 10^5, so enumerating them is far too slow. You need to update the answer for a whole batch of subarrays at once.

Sweep the right endpoint

Process j = 1..n (1-indexed) as the right end. For every left end i ≤ j, let d[i] be the number of distinct values in nums[i..j]. Keep

  • T = Σ d[i]^2 over i ≤ j, the sum of squared distinct counts of all subarrays ending at j.

The final answer is Σ_j T.

What changes when nums[j] arrives?

Let p be the previous index holding the same value (0 if there is none).

  • For left ends i ≤ p, the window already contained this value, so d[i] stays the same.
  • For left ends p < i ≤ j, the value is new, so d[i] goes up by one. This includes the new window [j..j], whose d goes from 0 to 1.

So each step is one range +1 on [L, R] = [p+1, j]. The squares change by

Σ_{i=L..R} ((d[i]+1)^2 − d[i]^2) = 2·Σ_{i=L..R} d[i] + (R − L + 1).

You only need the range sum of the old d values to update T. After that, apply the +1 to the range. The data structure therefore needs two operations: range add and range sum.

Fenwick tree refresher (the first two diagrams)

A Fenwick tree (BIT) over an array a[1..n] stores nodes t[i] = a[i−lowbit(i)+1] + … + a[i], where lowbit(i) = i & −i. Each node covers a block ending at i whose length is the lowest set bit of i.

  • Prefix query Q(i) = a[1]+…+a[i]: add t[i], then jump i −= lowbit(i) until you reach 0. Each jump clears one bit, so this is O(log n).
  • Point update a[i] += v: add v to t[i], then jump i += lowbit(i). These are exactly the nodes whose blocks contain i. Also O(log n).

A plain BIT does point update + prefix sum. You need range update + range sum.

Range add + range sum with two BITs

Store the difference array diff, where d[k] = diff[1] + … + diff[k]. Adding +v on [l, r] becomes two point updates: diff[l] += v and diff[r+1] −= v.

Now you need prefix sums of d, not of diff:

Σ_{k=1..i} d[k] = Σ_{t≤i} diff[t]·(i − t + 1) = (i+1)·Σ_{t≤i} diff[t] − Σ_{t≤i} diff[t]·t.

Keep two BITs:

  • B1 over diff[t]
  • B2 over diff[t]·t

Then prefix(i) = (i+1)·Q1(i) − Q2(i), and rangeSum(l, r) = prefix(r) − prefix(l−1). A range add touches each BIT twice. Every operation is O(log n).

(A lazy segment tree works equally well; the two-BIT trick is just shorter.)

Correctness in one breath

At step j, T is exactly the sum of squared distinct counts of the windows ending at j. The only windows whose count changes are those that do not already contain nums[j], which are the left ends after p. The algebra above updates T exactly. Summing T over all j counts every subarray once.

Walkthrough

Step 1. Fenwick structure (n = 8). Node t[i] stores the sum of a block that ends at i and has length lowbit(i) = i & −i. To get a[1..7], start at 7 and repeatedly strip the lowest bit: 7 → 6 → 4 → 0. The blue blocks t[7], t[6], t[4] tile [1..7] exactly, so the query takes O(log n).

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 340' font-family='sans-serif' font-size='14'><text x='20' y='30' fill='currentColor'>Fenwick blocks: t[i] covers (i − lowbit(i), i]</text><rect x='72' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='100' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t1</text><rect x='192' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='220' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t3</text><rect x='312' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='340' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t5</text><rect x='432' y='60' width='56' height='28' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><text x='460' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t7</text><rect x='72' y='100' width='116' height='28' fill='none' stroke='currentColor'/><text x='130' y='119' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t2</text><rect x='312' y='100' width='116' height='28' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><text x='370' y='119' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t6</text><rect x='72' y='140' width='236' height='28' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><text x='190' y='159' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t4</text><rect x='72' y='180' width='476' height='28' fill='none' stroke='currentColor'/><text x='310' y='199' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t8</text><g font-family='ui-monospace, monospace' fill='currentColor' text-anchor='middle'><text x='100' y='235'>1</text><text x='160' y='235'>2</text><text x='220' y='235'>3</text><text x='280' y='235'>4</text><text x='340' y='235'>5</text><text x='400' y='235'>6</text><text x='460' y='235'>7</text><text x='520' y='235'>8</text></g><text x='20' y='235' fill='currentColor'>i</text><text x='20' y='280' fill='currentColor' font-family='ui-monospace, monospace'>query(7) = t7 + t6 + t4</text><text x='20' y='308' fill='currentColor' font-family='ui-monospace, monospace'>i: 7 → 6 → 4 → 0   (i -= i &amp; -i)</text></svg>

Step 2. Point update. Adding to a[3] must reach every block that contains index 3. Repeatedly adding the lowest bit visits them all: 3 → 4 → 8. The amber blocks t[3], t[4], t[8] are exactly the blocks covering position 3. This is also O(log n).

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 340' font-family='sans-serif' font-size='14'><text x='20' y='30' fill='currentColor'>update(3, v): touch every block containing 3</text><rect x='72' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='100' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t1</text><rect x='192' y='60' width='56' height='28' fill='#f59e0b' fill-opacity='0.4' stroke='currentColor'/><text x='220' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t3</text><rect x='312' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='340' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t5</text><rect x='432' y='60' width='56' height='28' fill='none' stroke='currentColor'/><text x='460' y='79' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t7</text><rect x='72' y='100' width='116' height='28' fill='none' stroke='currentColor'/><text x='130' y='119' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t2</text><rect x='312' y='100' width='116' height='28' fill='none' stroke='currentColor'/><text x='370' y='119' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t6</text><rect x='72' y='140' width='236' height='28' fill='#f59e0b' fill-opacity='0.4' stroke='currentColor'/><text x='190' y='159' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t4</text><rect x='72' y='180' width='476' height='28' fill='#f59e0b' fill-opacity='0.4' stroke='currentColor'/><text x='310' y='199' text-anchor='middle' fill='currentColor' font-family='ui-monospace, monospace'>t8</text><line x1='220' y1='45' x2='220' y2='215' stroke='currentColor' stroke-dasharray='4 3'/><g font-family='ui-monospace, monospace' fill='currentColor' text-anchor='middle'><text x='100' y='235'>1</text><text x='160' y='235'>2</text><text x='220' y='235'>3</text><text x='280' y='235'>4</text><text x='340' y='235'>5</text><text x='400' y='235'>6</text><text x='460' y='235'>7</text><text x='520' y='235'>8</text></g><text x='20' y='235' fill='currentColor'>i</text><text x='20' y='280' fill='currentColor' font-family='ui-monospace, monospace'>update(3): t3, t4, t8 += v</text><text x='20' y='308' fill='currentColor' font-family='ui-monospace, monospace'>i: 3 → 4 → 8   (i += i &amp; -i)</text></svg>

Step 3. Sample [1,2,1], j = 1. The value 1 has not been seen before, so the range is [1,1]. The old sum of d on that range is 0, giving Δ = 2·0 + 1 = 1 and T = 1. Then apply the range +1: diff[1] += 1 and diff[2] −= 1. B1 holds diff and B2 holds diff·t. The rows show the logical arrays the two BITs sum over, not the raw t[] nodes.

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 340' font-family='sans-serif' font-size='14'><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='40'>1</text><text x='250' y='40'>2</text><text x='320' y='40'>3</text></g><text x='20' y='75' fill='currentColor'>nums</text><text x='20' y='135' fill='currentColor'>d (after)</text><text x='20' y='195' fill='currentColor'>B1: diff</text><text x='20' y='255' fill='currentColor'>B2: diff·t</text><rect x='150' y='50' width='60' height='40' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><rect x='220' y='50' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='50' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='110' width='60' height='40' fill='#22c55e' fill-opacity='0.35' stroke='currentColor'/><rect x='220' y='110' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='110' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='230' width='60' height='40' fill='none' stroke='currentColor'/><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='75'>1</text><text x='250' y='75'>2</text><text x='320' y='75'>1</text><text x='180' y='135'>1</text><text x='250' y='135'>0</text><text x='320' y='135'>0</text><text x='180' y='195'>1</text><text x='250' y='195'>-1</text><text x='320' y='195'>0</text><text x='180' y='255'>1</text><text x='250' y='255'>-2</text><text x='320' y='255'>0</text></g><g fill='currentColor' font-family='ui-monospace, monospace'><text x='390' y='70'>j=1, val 1, prev none</text><text x='390' y='100'>[L,R] = [1,1]</text><text x='390' y='130'>old sum d = 0</text><text x='390' y='160'>Δ = 2·0 + 1 = 1</text><text x='390' y='190'>T = 1</text><text x='390' y='220'>ans = 1</text></g><text x='20' y='310' fill='currentColor' font-family='ui-monospace, monospace'>prefix(i) = (i+1)·Q1(i) − Q2(i)</text></svg>

Step 4. j = 2, value 2, not seen before, so the range is [1,2]. The old sum is prefix(2) = 3·Q1(2) − Q2(2) = 3·0 − (−1) = 1, which matches the old d[1] + d[2] = 1 + 0. That gives Δ = 2·1 + 2 = 4 and T = 5 (the windows [1,2] → 4 and [2] → 1). Then the range add sets diff[1] += 1 and diff[3] −= 1. Now ans = 6.

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 340' font-family='sans-serif' font-size='14'><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='40'>1</text><text x='250' y='40'>2</text><text x='320' y='40'>3</text></g><text x='20' y='75' fill='currentColor'>nums</text><text x='20' y='135' fill='currentColor'>d (after)</text><text x='20' y='195' fill='currentColor'>B1: diff</text><text x='20' y='255' fill='currentColor'>B2: diff·t</text><rect x='150' y='50' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='50' width='60' height='40' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><rect x='290' y='50' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='110' width='60' height='40' fill='#22c55e' fill-opacity='0.35' stroke='currentColor'/><rect x='220' y='110' width='60' height='40' fill='#22c55e' fill-opacity='0.35' stroke='currentColor'/><rect x='290' y='110' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='230' width='60' height='40' fill='none' stroke='currentColor'/><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='75'>1</text><text x='250' y='75'>2</text><text x='320' y='75'>1</text><text x='180' y='135'>2</text><text x='250' y='135'>1</text><text x='320' y='135'>0</text><text x='180' y='195'>2</text><text x='250' y='195'>-1</text><text x='320' y='195'>-1</text><text x='180' y='255'>2</text><text x='250' y='255'>-2</text><text x='320' y='255'>-3</text></g><g fill='currentColor' font-family='ui-monospace, monospace'><text x='390' y='70'>j=2, val 2, prev none</text><text x='390' y='100'>[L,R] = [1,2]</text><text x='390' y='130'>old sum d = 1</text><text x='390' y='160'>Δ = 2·1 + 2 = 4</text><text x='390' y='190'>T = 1 + 4 = 5</text><text x='390' y='220'>ans = 1 + 5 = 6</text></g><text x='20' y='310' fill='currentColor' font-family='ui-monospace, monospace'>prefix(i) = (i+1)·Q1(i) − Q2(i)</text></svg>

Step 5. j = 3, value 1, previous occurrence at index 1 (amber). Left end 1 already contains a 1, so only [2,3] gains. The old sum is prefix(3) − prefix(1) = 3 − 2 = 1, which matches d[2] + d[3] = 1 + 0. That gives Δ = 2·1 + 2 = 4 and T = 9 (windows [1,2,1] → 4, [2,1] → 4, [1] → 1). The range add changes diff[2] from −1 to 0. Final answer: 6 + 9 = 15.

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 640 340' font-family='sans-serif' font-size='14'><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='40'>1</text><text x='250' y='40'>2</text><text x='320' y='40'>3</text></g><text x='20' y='75' fill='currentColor'>nums</text><text x='20' y='135' fill='currentColor'>d (after)</text><text x='20' y='195' fill='currentColor'>B1: diff</text><text x='20' y='255' fill='currentColor'>B2: diff·t</text><rect x='150' y='50' width='60' height='40' fill='#f59e0b' fill-opacity='0.4' stroke='currentColor'/><rect x='220' y='50' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='50' width='60' height='40' fill='#3b82f6' fill-opacity='0.35' stroke='currentColor'/><rect x='150' y='110' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='110' width='60' height='40' fill='#22c55e' fill-opacity='0.35' stroke='currentColor'/><rect x='290' y='110' width='60' height='40' fill='#22c55e' fill-opacity='0.35' stroke='currentColor'/><rect x='150' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='170' width='60' height='40' fill='none' stroke='currentColor'/><rect x='150' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='220' y='230' width='60' height='40' fill='none' stroke='currentColor'/><rect x='290' y='230' width='60' height='40' fill='none' stroke='currentColor'/><g fill='currentColor' font-family='ui-monospace, monospace' text-anchor='middle'><text x='180' y='75'>1</text><text x='250' y='75'>2</text><text x='320' y='75'>1</text><text x='180' y='135'>2</text><text x='250' y='135'>2</text><text x='320' y='135'>1</text><text x='180' y='195'>2</text><text x='250' y='195'>0</text><text x='320' y='195'>-1</text><text x='180' y='255'>2</text><text x='250' y='255'>0</text><text x='320' y='255'>-3</text></g><g fill='currentColor' font-family='ui-monospace, monospace'><text x='390' y='70'>j=3, val 1, prev 1</text><text x='390' y='100'>[L,R] = [2,3]</text><text x='390' y='130'>old sum d = 1</text><text x='390' y='160'>Δ = 2·1 + 2 = 4</text><text x='390' y='190'>T = 5 + 4 = 9</text><text x='390' y='220'>ans = 6 + 9 = 15</text></g><text x='20' y='310' fill='currentColor' font-family='ui-monospace, monospace'>prefix(i) = (i+1)·Q1(i) − Q2(i)</text></svg>

Complexity

  • Time: O(n log n). Each index does one range-sum query and one range add, each a constant number of O(log n) BIT walks.
  • Memory: O(n + V). You need two BIT arrays of size n+2 and a last table over values (V = 10^5).

Pitfalls

  • Compute the range sum before applying the +1. The delta 2·Σd + len uses the old values.
  • Be consistent about indexing. With 1-indexed BITs, the range is [p+1, j], where p = 0 means the value has not been seen.
  • Skip the r+1 update when r+1 > n, or allocate size n+2 so it is harmless.
  • With B2 taken modulo, entries can be negative (the −v·(r+1) updates). Normalise with +MOD before reducing. Alternatively keep the BITs in exact 64-bit integers: the sum of d is at most about 10^10, which fits.
  • Overflow: T can reach about n^3 = 10^15, and the running answer exceeds 64 bits. Reduce ans (and T) modulo 10^9+7.
  • Do not mix up the two prefix sums. Q1(i) gives the value d[i], while (i+1)·Q1(i) − Q2(i) gives the sum d[1]+…+d[i].
  • An O(n^2) sweep that updates every d[i] individually is correct but times out at n = 10^5.

Solution sketch

last[value] = 0 for all values
B1, B2 = Fenwick trees of size n+2 (all zero)
T = 0; ans = 0

function bitAdd(B, i, v): while i <= n: B[i] += v; i += i & -i
function bitQuery(B, i): s = 0; while i > 0: s += B[i]; i -= i & -i; return s
function prefix(i): return (i+1)*bitQuery(B1, i) - bitQuery(B2, i)
function rangeSum(l, r): return prefix(r) - prefix(l-1)
function rangeAdd(l, r, v):
    bitAdd(B1, l, v);   bitAdd(B1, r+1, -v)
    bitAdd(B2, l, v*l); bitAdd(B2, r+1, -v*(r+1))

for j = 1..n:
    L = last[nums[j]] + 1; R = j
    T = (T + 2*rangeSum(L, R) + (R - L + 1)) mod M   // uses OLD d values
    rangeAdd(L, R, 1)
    ans = (ans + T) mod M
    last[nums[j]] = j
return ans