Algorithm lab prototype

KMP: why i does not move back

This lesson uses a browser-generated execution trace to connect code branches, pointer movement, boundary conditions, and the final return value in one repeatable walkthrough.

Current episode
Interactive prototype

Step through code, memory, stack frame, and CPU stage without loading a video file.

HTML interactive trace
KMP execution generated in the browser

Step through the same trace without loading a video file. The code line, memory cells, CPU stage, and stack frame are all rendered from structured data.

kmp.go
Code Trace
Complete strStr function. The highlighted row is the current program counter.
1
func strStr(haystack, needle string) int {// entry
2
n := len(haystack)// text length
3
m := len(needle)// pattern length
4
if m == 0 { return 0 }// empty pattern
5
if n < m { return -1 }// impossible
6
lps := buildLPS(needle)// pattern memory
7
PC8
i, j := 0, 0// two pointers
9
for i < n {// i only moves right
10
if haystack[i] == needle[j] {// current chars equal
11
i++
12
j++// advance together
13
} else if j > 0 {// some prefix matched
14
j = lps[j-1]// i does not move
15
} else {
16
i++// no memory
17
}
18
if j == m { return i-j }// return start
19
}
20
return -1// not found
21
}
Memory
haystack
i
a
0
b
1
a
2
b
3
c
4
a
5
b
6
c
7
a
8
c
9
b
10
a
11
b
12
needle
j
a
0
b
1
c
2
a
3
c
4
lps
0
0
0
1
0
2
1
3
0
4
Abstract CPU
LOAD
BRANCH
WRITE
compare-
branchprepare loop
Call Stack
strStr frame
FP 0x7ff0
SP 0x7fb8
addrslotvalue
0x7ff8ctrlreturn addrcaller+pc
0x7ff0ctrlsaved FP0x8010
0x7fe8paramshaystack*heap[H]
0x7fe0paramsneedle*heap[N]
0x7fd8localsn13
0x7fd0localsm5
0x7fc8localslps*heap[L]
0x7fc0localsi0
0x7fb8localsj0
read only
Initialize stack frame

The abstract machine starts by placing i, j, n, and m in the stack frame.

Step 1 of 1010%

Video fallback

The rendered MP4 versions stay available while the HTML player is being evaluated.

Episode 2

Code execution trace

Code line, i/j pointer movement, lps fallback, and return i-j.

Episode 3

Abstract machine trace

Program counter, stack frame, memory reads, branch decision, and write-back.

Boundary cases

Why empty needle returns 0, and why longer needle returns -1 before KMP starts.

buildLPS state

How i, length, and lps change when the pattern compares with itself.

Matching branches

Why j falls back through lps while haystack's i stays where it is.

How this fits into 5tldr

Step 1

Keep generated videos as versioned static assets under public/learning.

Step 2

Use one topic page per concept so each video has transcript, checkpoints, and follow-up practice.

Step 3

Start noindex for prototypes, then link from Resources or Learning Plans after the format works.

KMP Algorithm Code Trace | 5tldr | 5tldr