Perfect — let’s scale it up so it really “clicks”.
s = "abcdefghijk" // length n = 11
lengths = [10, 1, 4]
Each L means:
roll indices [0 .. L-1] by +1
So:
10 → affects indices 0..91 → affects index 04 → affects indices 0..3diff = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] // size n+1 = 12
diff[0] += 1
diff[10] -= 1
diff = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0]
diff[0] += 1
diff[1] -= 1
diff = [2, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0]
diff[0] += 1
diff[4] -= 1
diff = [3, -1, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0]
We now compute how many times each index is rolled.
running = 0
| i | diff[i] | running (roll count) |
|---|---|---|
| 0 | +3 | 3 |
| 1 | -1 | 2 |
| 2 | 0 | 2 |
| 3 | 0 | 2 |
| 4 | -1 | 1 |
| 5 | 0 | 1 |
| 6 | 0 | 1 |
| 7 | 0 | 1 |
| 8 | 0 | 1 |
| 9 | 0 | 1 |
| 10 | -1 | 0 |
[3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]
index: 0 1 2 3 4 5 6 7 8 9 10
char: a b c d e f g h i j k
rolls: 3 2 2 2 1 1 1 1 1 1 0
Apply shifts:
"ddeffghijkk"
👉 Each L adds:
+1 to [0 .. L-1]
👉 diff encodes:
start adding at 0
stop adding at L
👉 prefix sum converts that into:
actual roll count per index
Instead of thinking:
"for each index, check all lengths"
Think:
"each length paints a prefix — diff array stacks all paints efficiently"
If you want, next step I can show:
👉 how to solve this without diff using sorting + binary search (O(n log n)) — sometimes interviewers push that variant.