Perfect — let’s scale it up so it really “clicks”.


📦 Bigger Example

s = "abcdefghijk"   // length n = 11
lengths = [10, 1, 4]

🧠 Meaning of operations

Each L means:

roll indices [0 .. L-1] by +1

So:


Step 1 — Initialize diff

diff = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]   // size n+1 = 12

Step 2 — Apply updates

🔹 L = 10

diff[0] += 1
diff[10] -= 1
diff = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0]

🔹 L = 1

diff[0] += 1
diff[1] -= 1
diff = [2, -1, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0]

🔹 L = 4

diff[0] += 1
diff[4] -= 1
diff = [3, -1, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0]

⚡ Step 3 — Prefix sum (critical step)

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

✅ Final roll counts

[3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0]

🔤 Step 4 — Apply to string

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:


🎯 Final result

"ddeffghijkk"

🧠 What to remember (important)

👉 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

⚡ Intuition shortcut

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.