{"id":"build-kmp-prefix-table","title":"Build KMP Prefix Table","difficulty":"medium","patterns":["string-matching"],"primaryConcept":"string-match-prefix-function","concepts":["string-match-prefix-function"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"pattern","sizeMetric":"length","sizes":[8,16,32,64],"alphabet":"abac"},"description":"Given a string `pattern`, return its KMP prefix table `lps`.\n\n`lps[i]` is the length of the longest proper prefix of `pattern[0:i+1]` that is also a suffix of that same substring.\n\nThis table is the reusable preprocessing step behind KMP string matching.","examples":[{"input":"pattern = \"ababaca\"","output":"[0,0,1,2,3,0,1]","explanation":"At index 4, \"ababa\" has longest proper prefix-suffix \"aba\" of length 3."},{"input":"pattern = \"aaaa\"","output":"[0,1,2,3]","explanation":"Every new character extends the previous border by one."}],"constraints":[{"id":"1-len-pattern-10-5","text":"1 <= len(pattern) <= 10^5","check":{"kind":"sizeRange","target":"pattern","measure":"stringLength","min":1,"max":100000}},{"id":"pattern-contains-lowercase-english-letters","text":"pattern contains lowercase English letters","check":{"kind":"domain","target":"pattern","selector":"stringChars","allowed":["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]}}],"starterCode":"class Solution:\n    def buildPrefixTable(self, pattern: str) -> list[int]:\n        # Your code here\n        pass","functionName":"buildPrefixTable","testCases":[{"id":"1","input":{"pattern":"ababaca"},"expected":[0,0,1,2,3,0,1],"description":"Standard KMP prefix table sample."},{"id":"2","input":{"pattern":"aaaa"},"expected":[0,1,2,3],"description":"Every character extends the border."},{"id":"3","input":{"pattern":"abc"},"expected":[0,0,0],"description":"No repeated prefix-suffix border."},{"id":"4","input":{"pattern":"aabaacaabaa"},"expected":[0,1,0,1,2,0,1,2,3,4,5],"description":"Fallbacks and later border growth."},{"id":"5","input":{"pattern":"a"},"expected":[0],"description":"Single-character pattern."},{"id":"6","input":{"pattern":"ababcabab"},"expected":[0,0,1,2,0,1,2,3,4],"description":"Fallback after a partial border, then reuse of the prefix."},{"id":"h1","input":{"pattern":"aabaaab"},"description":"Repeated border with a late fallback.","expected":[0,1,0,1,2,2,3]},{"id":"h2","input":{"pattern":"abcdabca"},"description":"Border reappears only at the end.","expected":[0,0,0,0,1,2,3,1]},{"id":"h3","input":{"pattern":"abcabcabc"},"description":"Periodic pattern grows the border steadily.","expected":[0,0,0,1,2,3,4,5,6]},{"id":"h4","input":{"pattern":"zzzzxzzzz"},"description":"Long repeated prefix interrupted by a mismatch.","expected":[0,1,2,3,0,1,2,3,4]},{"id":"h5","input":{"pattern":"abcababcab"},"description":"A mismatch after a long border falls back before continuing.","expected":[0,0,0,1,2,1,2,3,4,5]},{"id":"h6","input":{"pattern":"aaaaabaaaaab"},"description":"Fallback can land on a shorter border and then grow again.","expected":[0,1,2,3,4,0,1,2,3,4,5,6]}],"hints":[{"level":1,"content":"Track the current border length while scanning the pattern from left to right."},{"level":2,"content":"On a match, extend the border and write that length into the current table slot."},{"level":3,"content":"On a mismatch, fall back to the previous border length instead of restarting from scratch."}],"guidedFlow":{"version":2,"progressRevision":"build-kmp-prefix-table-2026-07-19-derived-baseline-and-zero-border","approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"recheck-prefixes","name":"Check every prefix","summary":"For each index, compare every possible prefix and suffix character by character.","decisionReason":"This recomputes candidate borders from scratch for each position, walking up to n lengths and scanning up to n characters per comparison, so it discards the border length the scan already proved.","complexity":{"time":"O(n^3)","space":"O(n)"},"tradeoffs":["Simple to reason about locally, but it does not maintain a reusable current-border state across positions."],"isOptimal":false},{"id":"kmp-prefix","name":"KMP prefix table","summary":"Reuse the previous border length and fall back through the LPS table on mismatches.","decisionReason":"This is the intended approach because the scan preserves the current border length and uses the table to choose the next comparison state after a mismatch.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["The table costs O(n) space, but each comparison either advances the scan or reduces the maintained border state."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-lps","title":"Initialize LPS state","description":"Create one zero-seeded table entry for each pattern character.","commonMistakes":["Allocating the table with the wrong length","Starting every value as a nonzero border"],"hint":"The first prefix-table value is always 0.","semanticSpec":{"intent":"Initialize indexed result state for the prefix-function table.","doneWhen":"The solution creates a one-entry-per-character LPS table before the scan loop.","shouldFailWhen":"This step should fail if no indexed result table is created.","roles":["pattern","LPS table"],"mustProve":["A reusable indexed result state is initialized before prefix scanning."],"mustNotAccept":["A scalar border value without an indexed table."],"proofSnippets":[{"id":"py-build-kmp-prefix-init-lps","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]}},{"id":"handle-match","title":"Extend border on match","description":"When the current character matches the border character, grow the border and write it into LPS.","commonMistakes":["Advancing i without writing lps[i]","Comparing against the wrong border character"],"hint":"A match means the current prefix-suffix border is one character longer.","semanticSpec":{"intent":"Populate the prefix-function table on character matches.","doneWhen":"The solution compares pattern[i] to pattern[length], increments length on a match, writes lps[i], and advances i.","shouldFailWhen":"This step should fail if the table is not updated from the border length on a match.","roles":["scan index","border length","LPS table"],"mustProve":["The border length extends after an indexed pattern-character match.","The current LPS slot receives the extended border length."],"mustNotAccept":["Writing a constant value on every match."],"proofSnippets":[{"id":"py-build-kmp-prefix-handle-match","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        else:\n            i += 1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"extends_prefix_border_on_match","scope":"handle-match","readMode":"string-matching-value-query-v1"}]}},{"id":"handle-mismatch","title":"Fall back on mismatch","description":"When a mismatch happens after a positive border, reuse the previous LPS value as the next border.","commonMistakes":["Resetting length to 0 immediately","Advancing i during a fallback before retrying the comparison"],"hint":"Fallback changes length, not i.","semanticSpec":{"intent":"Use the prefix table to fall back to the previous valid border on mismatch.","doneWhen":"The solution assigns `length = lps[length - 1]` when length is positive and the current characters mismatch.","shouldFailWhen":"This step should fail if mismatches restart from scratch instead of using LPS fallback.","roles":["border length","previous LPS value","mismatch branch"],"mustProve":["A positive border mismatch does not advance the scan index immediately.","The next candidate border comes from an earlier LPS entry.","The same current character is compared again after the border state changes."],"mustNotAccept":["Recomputing the prefix from the beginning.","Dropping the positive border without consulting the table."],"proofSnippets":[{"id":"py-build-kmp-prefix-handle-mismatch","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"falls_back_to_previous_prefix_border","scope":"handle-mismatch","readMode":"string-matching-value-query-v1"}]}},{"id":"zero-border-mismatch","title":"Advance after zero-border mismatch","description":"When a mismatch occurs with border length already zero, resolve the current LPS slot to 0 and advance the scan index.","commonMistakes":["Retrying forever when length is already zero","Advancing after overwriting the zero LPS value with a nonzero value"],"hint":"With no shorter border to fall back to, the current position is resolved as 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"builds_prefix_function_table","scope":"zero-border-mismatch","readMode":"string-matching-value-query-v1"}]},"semanticSpec":{"intent":"Handle the mismatch branch when no candidate border remains.","doneWhen":"This step is done when a mismatch at length 0 records or preserves lps[i] = 0 and advances i to the next position.","shouldFailWhen":"This step should fail if the scan gets stuck at the same index, falls back below zero, or leaves the LPS slot unresolved.","roles":["current index","zero border length","LPS slot","scan advance"],"mustProve":["The branch detects mismatch with border length 0.","The current LPS entry is resolved as 0.","The scan advances to the next index."],"mustNotAccept":["Retrying the same comparison forever.","Changing length to a negative value."],"equivalentVariants":["Explicitly write 0 then increment i.","Rely on zero-initialized LPS storage while still advancing i."],"proofSnippets":[{"id":"py-build-kmp-prefix-zero-border-mismatch","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]\n        else:\n            lps[i] = 0\n            i += 1"}]}},{"id":"return-table","title":"Return the table","description":"Return the completed LPS table.","commonMistakes":["Returning the final border length instead of the table","Returning the input pattern"],"hint":"The caller needs every table slot, not only the last one.","semanticSpec":{"intent":"Return the populated prefix-function table.","doneWhen":"The solution returns the LPS table after the prefix scan completes.","shouldFailWhen":"This step should fail if the terminal return is not the result sequence.","roles":["LPS table","terminal return"],"mustProve":["The indexed result sequence is returned."],"mustNotAccept":["Returning only the scalar border length."],"proofSnippets":[{"id":"py-build-kmp-prefix-return-table","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]\n        else:\n            lps[i] = 0\n            i += 1\n    return lps"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}],"slides":[{"id":"read-the-problem","kind":"info","chapter":"The table","eyebrow":"Read the problem","title":"The longest border at every position","workspacePanel":"problem","body":["For a pattern, lps[i] is the length of the longest proper prefix of pattern[0..i] that is also a suffix of that same piece. A border, in short: a chunk that opens the substring and also closes it, but is not the whole substring.","Testing every possible border at every position repeats earlier comparisons. When a match breaks, a shorter border already recorded in lps can be the next candidate."]},{"id":"direct-entry-probe","kind":"case-probe","chapter":"The obvious way","eyebrow":"Start with one entry","title":"If you only needed lps[4] for \"abcab\", how could you find it directly?","workspacePanel":"problem","summary":"A border must be shorter than the whole piece, so the candidate lengths for \"abcab\" are 4, 3, 2, and 1.","options":[{"id":"longest-down","label":"Try candidate lengths from 4 down and stop at the first prefix-suffix match","rationale":"The first match found while shrinking is the longest proper border, which is exactly the value lps[4] asks for.","isCorrect":true},{"id":"shortest-up","label":"Try lengths from 1 up and stop at the first match","rationale":"The first match from the short end need not be the longest border, so stopping there can record too small a value."},{"id":"count-ends","label":"Count how often the first and last characters appear","rationale":"A border depends on the characters appearing in the same order, which endpoint counts cannot prove."}],"answer":"Try the longest legal prefix against the same-length suffix, then shorten until they match. For \"abcab\", lengths 4 and 3 fail and length 2 matches \"ab\" with \"ab\". Applying that direct search at every index gives us a correct baseline to trace."},{"id":"brute-force","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"For each position, test every prefix length from longest down","summary":"Testing every prefix length at every index gets each answer right, but each position runs its own full search and recompares what the position before it already settled. Watch how much of that work repeats.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"lps = [0] * len(pattern)\nfor i in range(1, len(pattern)):\n    for L in range(i, 0, -1):\n        if pattern[0:L] == pattern[i - L + 1:i + 1]:\n            lps[i] = L\n            break\nreturn lps","steps":[{"id":"try-long","title":"At index 4, start with the longest candidate border and shrink","codeLine":4,"summary":"For index 4 (\"abcab\") the test starts at length 4 and works down: \"abca\" against \"bcab\" fails, \"abc\" against \"cab\" fails, until \"ab\" against \"ab\" matches.","state":{"s":"abcaba","i":4,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,null,null]}],"current":4,"candidateL":4}},{"id":"found-four","title":"Index 4 settles on length 2 after testing lengths 4 and 3 first","codeLine":5,"summary":"\"ab\" opens \"abcab\" and also ends it, so lps[4] is 2, but only after lengths 4 and 3 were built and compared and thrown away.","state":{"s":"abcaba","i":4,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":4,"foundL":2}},{"id":"redo-five","title":"Index 5 starts the same shrinking search over from scratch","codeLine":4,"summary":"For index 5 (\"abcaba\") the search again begins at the longest length and walks down, recomparing prefixes the previous index already examined.","state":{"s":"abcaba","i":5,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5,"candidateL":5}},{"id":"found-five","title":"Index 5 settles on length 1","codeLine":5,"summary":"Only the single \"a\" opens and closes \"abcaba\", so lps[5] is 1. Every position paid for its own full top-down scan.","state":{"s":"abcaba","i":5,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,1]}],"current":5,"foundL":1}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nfor (let i = 1; i < pattern.length; i++) {\n    for (let L = i; L >= 0; L--) {\n        if (pattern.slice(0, L) === pattern.slice(((i - L) + 1), (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nfor (let i = 1; i < pattern.length; i++) {\n    for (let L = i; L >= 0; L--) {\n        if (pattern.slice(0, L) === pattern.slice(((i - L) + 1), (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> lps = new ArrayList<>();\nfor (int index = 0; index < pattern.length(); index++) {\n    lps.add(0);\n}\nfor (int i = 1; i < pattern.length(); i++) {\n    for (int L = i; L > 0; L--) {\n        if (pattern.substring(0, L).equals(pattern.substring(((i - L) + 1), (i + 1)))) {\n            lps.set(i, L);\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":13},"statementBundles":{"1":{"startLine":1,"endLine":4},"6":{"startLine":9,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> lps = Enumerable.Repeat<int>(0, pattern.Length).ToList();\nfor (int i = 1; i < pattern.Length; i++) {\n    for (int L = i; L > 0; L--) {\n        if (pattern.Substring(0, L) == pattern.Substring(i - L + 1, (i + 1) - (i - L + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> lps = vector<int>(pattern.size(), 0);\nfor (int i = 1; i < pattern.size(); i++) {\n    for (int L = i; L > 0; L--) {\n        if (string(pattern.begin() + 0, pattern.begin() + L) == string(pattern.begin() + ((i - L) + 1), pattern.begin() + (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}}}},"body":["For each index, compare the whole prefix to the matching suffix, then shorter and shorter, stopping at the first length that matches."]},{"id":"waste-probe","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the cost","title":"For a pattern of length n, how much work does this top-down search do?","workspacePanel":"trace","summary":"The trace for index 5 restarts work that index 4 already did.","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"lps = [0] * len(pattern)\nfor i in range(1, len(pattern)):\n    for L in range(i, 0, -1):\n        if pattern[0:L] == pattern[i - L + 1:i + 1]:\n            lps[i] = L\n            break\nreturn lps","steps":[{"id":"redo-from-top","title":"Index 5 starts its candidate scan back at the longest length","codeLine":3,"summary":"With the table already at [0, 0, 0, 1, 2], index 5 still opens at candidate length 5 and walks every shorter length down, re-running prefix-versus-suffix tests that index 4 already settled.","state":{"s":"abcaba","i":5,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5,"candidateL":5}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nfor (let i = 1; i < pattern.length; i++) {\n    for (let L = i; L >= 0; L--) {\n        if (pattern.slice(0, L) === pattern.slice(((i - L) + 1), (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nfor (let i = 1; i < pattern.length; i++) {\n    for (let L = i; L >= 0; L--) {\n        if (pattern.slice(0, L) === pattern.slice(((i - L) + 1), (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"List<Integer> lps = new ArrayList<>();\nfor (int index = 0; index < pattern.length(); index++) {\n    lps.add(0);\n}\nfor (int i = 1; i < pattern.length(); i++) {\n    for (int L = i; L > 0; L--) {\n        if (pattern.substring(0, L).equals(pattern.substring(((i - L) + 1), (i + 1)))) {\n            lps.set(i, L);\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":5,"3":6,"4":7,"5":8,"6":9,"7":13},"statementBundles":{"1":{"startLine":1,"endLine":4},"6":{"startLine":9,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> lps = Enumerable.Repeat<int>(0, pattern.Length).ToList();\nfor (int i = 1; i < pattern.Length; i++) {\n    for (int L = i; L > 0; L--) {\n        if (pattern.Substring(0, L) == pattern.Substring(i - L + 1, (i + 1) - (i - L + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> lps = vector<int>(pattern.size(), 0);\nfor (int i = 1; i < pattern.size(); i++) {\n    for (int L = i; L > 0; L--) {\n        if (string(pattern.begin() + 0, pattern.begin() + L) == string(pattern.begin() + ((i - L) + 1), pattern.begin() + (i + 1))) {\n            lps[i] = L;\n            break;\n        }\n    }\n}\nreturn lps;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":10},"statementBundles":{"6":{"startLine":6,"endLine":9}}}}},"options":[{"id":"cubic","label":"Up to about n candidate lengths per index, each comparison scanning up to n characters: O(n cubed)","rationale":"Each of the n indices walks up to n candidate lengths, and every prefix-versus-suffix test compares up to n characters, so three factors of n multiply.","isCorrect":true},{"id":"quadratic","label":"Up to about n candidate lengths per index, but each comparison is free: O(n squared)","rationale":"A full prefix-versus-suffix comparison is not free; it walks up to n characters, so the per-comparison scan adds a third factor of n."},{"id":"linear","label":"A constant amount per index, so about n in total","rationale":"A single index can walk many candidate lengths before one matches, and each comparison scans characters, so the per-index work is not constant."}],"answer":"Up to n candidate lengths per index, and each comparison scans up to n characters, so the direct prefix-versus-suffix search is O(n cubed). Index 5 redid comparisons index 4 had already proved, which is the repeated work to remove."},{"id":"carry-bridge","kind":"info","chapter":"The idea","eyebrow":"Stop restarting","title":"Each index threw away the last one's work","workspacePanel":"visualizer","body":["The top-down search paid an O(n cubed) bill because every index restarted from the longest candidate, recomparing prefixes against suffixes the position before it had already tested.","By the time the scan reaches index 5, the table already holds [0, 0, 0, 1, 2] for everything before it. That filled-in table is a record of matches the search already proved. What could it read from there to avoid starting each index from scratch?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"bridge-state","state":{"s":"abcaba","i":5,"labels":{"s":"pattern","i":"i"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5}}]}},{"id":"carry-border","kind":"case-probe","chapter":"The idea","eyebrow":"Find the state","title":"Scanning left to right, what single number is worth carrying between positions?","workspacePanel":"visualizer","summary":"pattern = \"abcaba\", and the scan has filled lps through index 4 as [0, 0, 0, 1, 2].","options":[{"id":"border-length","label":"The length of the border confirmed so far","rationale":"If the border up to the last position has length 2, the next character only has to extend that match by one; the length is the running progress every position hands to the next.","isCorrect":true},{"id":"all-lengths","label":"The full set of every prefix length tested at the last index","rationale":"Keeping every tested length is the brute force again; one number, the current border length, already captures the progress that matters."},{"id":"char-counts","label":"How many times each character has appeared","rationale":"Borders depend on the order of characters, not their frequencies, so counts cannot tell you how far a prefix matches a suffix."}],"answer":"The current border length. It says how many characters of the prefix already match the suffix ending here, so the next position extends that progress instead of rebuilding it.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"carry-state","state":{"s":"abcaba","i":4,"j":2,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":4}}]}},{"id":"mismatch-fallback","kind":"case-probe","chapter":"The idea","eyebrow":"Find the key rule","title":"The next character breaks the current match. Where can the search resume?","workspacePanel":"visualizer","summary":"At i = 5, j = 2, pattern[5] = \"a\", and pattern[j] = \"c\".","options":[{"id":"shorter-border","label":"At the border of that length-2 prefix, found in lps[length - 1]","rationale":"The length-2 match \"ab\" has its own longest border stored in lps[1]. Resuming there tries the next-shorter prefix that is still guaranteed to match the suffix, so no confirmed progress is rechecked.","isCorrect":true},{"id":"restart-zero","label":"Back at length 0, comparing against the very first character again","rationale":"Dropping straight to 0 throws away every shorter prefix that already matches; for \"abcaba\" that loses the recovery to length 1 at index 5, giving 0 where the answer is 1."},{"id":"advance-on","label":"Nowhere: record 0 and move to the next index","rationale":"Recording 0 and advancing skips the shorter borders entirely; the same character still has a smaller prefix it could match, so the position is not finished yet."}],"answer":"At lps[length - 1]. The broken length-2 prefix has its own border length stored there, so the search falls back to that shorter prefix and compares the same character again, never rechecking what already matched.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"fallback-state","state":{"s":"abcaba","i":5,"j":2,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5}}]}},{"id":"approach-selection","kind":"info","chapter":"The idea","eyebrow":"Name what you derived","title":"This moving-border scan is the KMP prefix-table construction","workspacePanel":"visualizer","body":["You have already built its two decisions: carry the border length forward on a match, and fall back through lps[length - 1] on a mismatch without advancing the scan.","That is the KMP prefix-table method. The scan advances i at most n times. length can grow only on one of those advances, and every fallback strictly undoes some of that accumulated growth, so all fallback steps together are also bounded by the growth. The total scan is O(n), and the table uses O(n) space."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"s":"abcaba","labels":{"s":"pattern"},"arrays":[{"name":"lps","values":[0,0,0,1,2,1]}]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"One border length, carried and revised","workspacePanel":"visualizer","body":["length starts at 0 and i starts at 1. On a match, length grows by one and that new length is written into lps[i] before i advances. On a mismatch with a positive length, the search falls back to lps[length - 1] and retries the same i.","The trace will run a stretch of matches, then a mismatch that triggers the fallback, and you will watch whether the scan advances or retries the same index. Predict each step before it resolves."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"s":"abcaba","i":1,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,null,null,null,null,null]}],"current":1}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Build the table","title":"Build the table for \"abcaba\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"idx3-match","state":{"s":"abcaba","i":3,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,null,null,null]}],"current":3}},{"id":"idx4-match","state":{"s":"abcaba","i":4,"j":1,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,null,null]}],"current":4}},{"id":"idx5-mismatch","state":{"s":"abcaba","i":5,"j":2,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5}},{"id":"idx5-recover","state":{"s":"abcaba","i":5,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":5}}]},"beats":[{"id":"idx3-match","title":"At index 3 with length 0, pattern[3] = \"a\" meets pattern[0] = \"a\". What happens?","summary":"length = 0, i = 3, pattern[3] = \"a\", pattern[0] = \"a\".","options":[{"id":"extend","label":"length becomes 1 and lps[3] is set to 1","rationale":"The characters match, so the border grows from 0 to 1 and that length is written into the current slot before i moves on.","isCorrect":true},{"id":"stay","label":"length stays 0 and lps[3] is set to 0","rationale":"A match must grow the border; leaving length at 0 would ignore that pattern[3] reopens the prefix \"a\"."},{"id":"jump","label":"length jumps to 3 to match the index","rationale":"The border grows by exactly one per match. It tracks confirmed prefix length; the position index is 3."}],"answer":"length becomes 1 and lps[3] is written as 1. A match extends the border by one and records it."},{"id":"idx4-match","title":"Now length is 1 and pattern[4] = \"b\" meets pattern[1] = \"b\". The result?","summary":"length = 1, i = 4, comparing pattern[4] to pattern[length].","options":[{"id":"grow","label":"length becomes 2 and lps[4] is set to 2","rationale":"The border was \"a\" and now \"ab\" matches both ends of \"abcab\", so the length climbs to 2 and is recorded.","isCorrect":true},{"id":"reset","label":"length resets to 0 because a new run begins","rationale":"There is no reset on a match; the border extends from its current length, carrying the \"a\" already confirmed."},{"id":"stuck","label":"length stays 1 since only one pair matched","rationale":"Each successful match adds one; the prior \"a\" plus this \"b\" makes a confirmed border of length 2."}],"answer":"length becomes 2 and lps[4] is 2. The confirmed border is now \"ab\"."},{"id":"idx5-mismatch","title":"At index 5, length is 2 but pattern[5] = \"a\" does not equal pattern[2] = \"c\". What changes?","summary":"length = 2, i = 5, the growing border just broke.","options":[{"id":"fallback","label":"length drops to lps[1] = 0, and i stays at 5","rationale":"A positive border that breaks falls back to lps[length - 1]: lps[1] is 0, so length becomes 0 while i holds, ready to retry the same character.","isCorrect":true},{"id":"record-zero","label":"lps[5] is written as 0 right now because the match failed","rationale":"A mismatch does not write the slot yet; lps[5] is only set once the retries resolve, and falling back may still recover a positive border here."},{"id":"keep","label":"length stays 2 and i advances to 6","rationale":"The match failed, so the length-2 border cannot stand; it must shrink before the comparison is retried."}],"answer":"length falls back to lps[1] = 0 while i stays at 5. The broken border shrinks to its own border, and the same character is about to be compared again."},{"id":"idx5-recover","title":"With length now 0, pattern[5] = \"a\" is compared to pattern[0] = \"a\". How does index 5 finish?","summary":"length = 0, i = 5, retrying the same character against the start.","options":[{"id":"recover","label":"They match, so length becomes 1 and lps[5] is set to 1","rationale":"The fallback exposed the single \"a\" prefix, which does match the trailing \"a\", so the position recovers a border of length 1 that a straight reset to 0 would have missed.","isCorrect":true},{"id":"zero","label":"lps[5] is recorded as 0","rationale":"The retry against pattern[0] matches, so the answer is 1, not 0; recording 0 is exactly the value the fallback exists to avoid."},{"id":"fallback-again","label":"length falls back once more below 0","rationale":"Fallback only happens on a mismatch with a positive length; here length is 0 and the characters match, so the border grows instead."}],"answer":"They match, so length becomes 1 and lps[5] is 1. Falling back instead of resetting recovered the real border, giving [0, 0, 0, 1, 2, 1]."}]},{"id":"zero-border-stop","kind":"case-probe","chapter":"Trace","eyebrow":"Finish the branch","title":"The characters mismatch and length is already 0. What settles this position?","workspacePanel":"visualizer","summary":"At i = 1 in \"abcaba\", pattern[1] = \"b\" does not match pattern[0] = \"a\", and there is no shorter border left to try.","options":[{"id":"write-zero-advance","label":"Leave lps[1] at 0 and advance i","rationale":"With length already 0, no nonempty candidate border remains. The current answer is 0, so this position is finished and the scan can move on.","isCorrect":true},{"id":"retry-same","label":"Keep i in place and retry the same comparison","rationale":"Neither i nor length would change, so this repeats the same failed comparison forever."},{"id":"negative-border","label":"Reduce length to -1 and compare again","rationale":"A border length cannot be negative; reaching 0 means the fallback chain is exhausted."}],"answer":"Resolve lps[i] as 0 and advance i. Positive length gives the scan somewhere shorter to fall back; length 0 does not, so the current position is complete.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-border-state","state":{"s":"abcaba","i":1,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,null,null,null,null,null]}],"current":1}}]}},{"id":"advance-i-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"On a fallback, should i move forward too?","workspacePanel":"trace","summary":"The fallback shrinks length to lps[length - 1]. Every other branch advances i right after it acts, so adding i += 1 here looks consistent. Watch the table it builds for \"abcaba\".","pitfall":"The code below shrinks length on a mismatch and advances i in the same branch.","whyItMatters":"Falling back is only half the move: the point of shrinking length is to compare the same character again. Advancing i skips that retry, so the recovered \"a\" at index 5 is never found and its slot stays 0 where the true border is 1, giving [0, 0, 0, 1, 2, 0] instead of [0, 0, 0, 1, 2, 1]. Keep i fixed on the fallback branch; only the match branch and the zero-border branch move i forward.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"lps = [0] * len(pattern)\nlength = 0\ni = 1\nwhile i < len(pattern):\n    if pattern[i] == pattern[length]:\n        length += 1\n        lps[i] = length\n        i += 1\n    elif length != 0:\n        length = lps[length - 1]\n        i += 1\n    else:\n        lps[i] = 0\n        i += 1","steps":[{"id":"grow-to-two","title":"The border grows to 2 across \"abcab\"","codeLine":7,"summary":"By index 4 the matches have built a confirmed border \"ab\", so length is 2 and lps[4] is 2.","state":{"s":"abcaba","i":4,"j":2,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,null]}],"current":4}},{"id":"fallback-bumps-i","title":"The mismatch at index 5 shrinks length but also moves i","codeLine":11,"summary":"pattern[5] = \"a\" breaks the length-2 border. The fallback sets length to lps[1] = 0, then the same branch runs i += 1, so i jumps to 6 and the scan abandons index 5 with its slot left at the zero seed.","state":{"s":"abcaba","i":6,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,0]}]}},{"id":"skipped","title":"The loop guard ends the scan with index 5 still 0","codeLine":4,"summary":"With i now 6, the guard 6 < 6 is false and the loop exits. Index 5 was never compared to pattern[0], so its zero-seeded slot stands, giving [0, 0, 0, 1, 2, 0] where the true border is 1.","state":{"s":"abcaba","i":6,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,1,2,0]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nlet length = 0;\nlet i = 1;\nwhile (i < pattern.length) {\n    if (pattern[i] === pattern[length]) {\n        length++;\n        lps[i] = length;\n        i++;\n    } else {\n        if (length !== 0) {\n            length = lps[(length - 1)];\n            i++;\n        } else {\n            lps[i] = 0;\n            i++;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15},"statementBundles":{"8":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":18}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const lps = Array(pattern.length).fill(0);\nlet length = 0;\nlet i = 1;\nwhile (i < pattern.length) {\n    if (pattern[i] === pattern[length]) {\n        length++;\n        lps[i] = length;\n        i++;\n    } else {\n        if (length !== 0) {\n            length = lps[(length - 1)];\n            i++;\n        } else {\n            lps[i] = 0;\n            i++;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15},"statementBundles":{"8":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":18}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int[] lps = new int[pattern.length()];\nint length = 0;\nint i = 1;\nwhile (i < pattern.length()) {\n    if (pattern.charAt(i) == pattern.charAt(length)) {\n        length++;\n        lps[i] = length;\n        i++;\n    } else {\n        if (length != 0) {\n            length = lps[(length - 1)];\n            i++;\n        } else {\n            lps[i] = 0;\n            i++;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15},"statementBundles":{"8":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":18}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"List<int> lps = Enumerable.Repeat<int>(0, pattern.Length).ToList();\nint length = 0;\nint i = 1;\nwhile (i < pattern.Length) {\n    if (pattern[i] == pattern[length]) {\n        length++;\n        lps[i] = length;\n        i++;\n    } else {\n        if (length != 0) {\n            length = lps[length - 1];\n            i++;\n        } else {\n            lps[i] = 0;\n            i++;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15},"statementBundles":{"8":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":18}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"vector<int> lps = vector<int>(pattern.size(), 0);\nint length = 0;\nsize_t i = 1;\nwhile (i < pattern.size()) {\n    if (pattern[static_cast<int>(i)] == pattern[length]) {\n        length++;\n        lps[static_cast<int>(i)] = length;\n        i++;\n    } else {\n        if (length != 0) {\n            length = lps[(length - 1)];\n            i++;\n        } else {\n            lps[static_cast<int>(i)] = 0;\n            i++;\n        }\n    }\n}","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":10,"10":11,"11":12,"12":13,"13":14,"14":15},"statementBundles":{"8":{"startLine":8,"endLine":9},"14":{"startLine":15,"endLine":18}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Advancing i during a positive-length fallback failed, so reject that shortcut. From here on, use the corrected rule: change only length during fallback, then retry the same i.","First a one-character pattern, \"a\", with no index to scan. Then \"aabaaac\", whose long run of \"a\"s builds a border that the final \"c\" breaks. For each, work out what the loop does before you answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"s":"aabaaac","i":1,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,null,null,null,null,null,null]}],"current":1}}]}},{"id":"single-char-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"For a one-character pattern, what does the loop do?","workspacePanel":"visualizer","summary":"lps starts as [0] and the scan starts at i = 1.","options":[{"id":"no-work","label":"Nothing: i = 1 is already past the only index, so lps stays [0]","rationale":"A proper prefix must be shorter than the whole substring, and a single character has none, so lps[0] is 0 and the loop body never runs.","isCorrect":true},{"id":"one","label":"It records lps[0] = 1 for the single character","rationale":"A border must be a proper prefix, strictly shorter than the substring, so a lone character borders nothing and lps[0] is 0."},{"id":"crash","label":"It reads past the end comparing index 1","rationale":"The loop guard i < len(pattern) is 1 < 1, false, so the body is skipped and nothing reads out of range."}],"answer":"Nothing runs. lps[0] is seeded to 0 and i = 1 is already past the end, so the single-character table is just [0].","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-state","state":{"s":"a","labels":{"s":"pattern"},"arrays":[{"name":"lps","values":[0]}]}}]}},{"id":"double-fallback-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"If one fallback still mismatches, what does the search do next?","workspacePanel":"visualizer","summary":"For \"aabaaac\" at index 6, one fallback already dropped length from 2 to 1, but pattern[6] = \"c\" still does not equal pattern[1] = \"a\".","options":[{"id":"again","label":"Fall back again to lps[length - 1] and retry the same character","rationale":"Each fallback shrinks the border by one stored step; if the retry still fails and length is positive, the search falls back once more, repeating until it matches or length reaches 0.","isCorrect":true},{"id":"advance-now","label":"Give up on borders and advance i with lps[i] = 0","rationale":"i only advances once length has reached 0; while length is still positive there is a shorter border left to test against the same character."},{"id":"restart-full","label":"Reset length to 0 immediately and move on","rationale":"Jumping to 0 skips the shorter borders between the current length and 0, which is exactly the matches the table was built to reuse."}],"answer":"It falls back again to lps[0] = 0 and retries the same character. Each fallback shrinks the border by one stored step, looping until one matches or length reaches 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"double-state","state":{"s":"aabaaac","i":6,"j":1,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,1,0,1,2,2,null]}]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"One border length carries the whole scan.","body":["Seed the table with a zero per character and start the scan one position in, carrying a single border length. On a match, grow the border, record it, and step forward.","On a mismatch, fall back through the stored borders without moving forward, and only step forward once the border is gone. Return the filled table."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"s":"abcaba","i":1,"j":0,"labels":{"s":"pattern","i":"i","j":"length"},"arrays":[{"name":"lps","values":[0,0,0,0,0,0]}],"current":1}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the prefix table","eyebrow":"Code the rule","summary":"Now turn the moving border into code: seed a zero per character, extend the border and record it on a match, fall back through lps on a mismatch without moving forward, write 0 and step ahead once the border is gone, then return the table.","workspacePanel":"code","checkpoints":[{"id":"init-lps","title":"Initialize LPS state","description":"Create one zero-seeded table entry for each pattern character.","commonMistakes":["Allocating the table with the wrong length","Starting every value as a nonzero border"],"hint":"The first prefix-table value is always 0.","semanticSpec":{"intent":"Initialize indexed result state for the prefix-function table.","doneWhen":"The solution creates a one-entry-per-character LPS table before the scan loop.","shouldFailWhen":"This step should fail if no indexed result table is created.","roles":["pattern","LPS table"],"mustProve":["A reusable indexed result state is initialized before prefix scanning."],"mustNotAccept":["A scalar border value without an indexed table."],"proofSnippets":[{"id":"py-build-kmp-prefix-init-lps","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"initializes_result_sequence","scope":"init-result","readMode":"array-scan-value-query-v1"}]}},{"id":"handle-match","title":"Extend border on match","description":"When the current character matches the border character, grow the border and write it into LPS.","commonMistakes":["Advancing i without writing lps[i]","Comparing against the wrong border character"],"hint":"A match means the current prefix-suffix border is one character longer.","semanticSpec":{"intent":"Populate the prefix-function table on character matches.","doneWhen":"The solution compares pattern[i] to pattern[length], increments length on a match, writes lps[i], and advances i.","shouldFailWhen":"This step should fail if the table is not updated from the border length on a match.","roles":["scan index","border length","LPS table"],"mustProve":["The border length extends after an indexed pattern-character match.","The current LPS slot receives the extended border length."],"mustNotAccept":["Writing a constant value on every match."],"proofSnippets":[{"id":"py-build-kmp-prefix-handle-match","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        else:\n            i += 1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"extends_prefix_border_on_match","scope":"handle-match","readMode":"string-matching-value-query-v1"}]}},{"id":"handle-mismatch","title":"Fall back on mismatch","description":"When a mismatch happens after a positive border, reuse the previous LPS value as the next border.","commonMistakes":["Resetting length to 0 immediately","Advancing i during a fallback before retrying the comparison"],"hint":"Fallback changes length, not i.","semanticSpec":{"intent":"Use the prefix table to fall back to the previous valid border on mismatch.","doneWhen":"The solution assigns `length = lps[length - 1]` when length is positive and the current characters mismatch.","shouldFailWhen":"This step should fail if mismatches restart from scratch instead of using LPS fallback.","roles":["border length","previous LPS value","mismatch branch"],"mustProve":["A positive border mismatch does not advance the scan index immediately.","The next candidate border comes from an earlier LPS entry.","The same current character is compared again after the border state changes."],"mustNotAccept":["Recomputing the prefix from the beginning.","Dropping the positive border without consulting the table."],"proofSnippets":[{"id":"py-build-kmp-prefix-handle-mismatch","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"falls_back_to_previous_prefix_border","scope":"handle-mismatch","readMode":"string-matching-value-query-v1"}]}},{"id":"zero-border-mismatch","title":"Advance after zero-border mismatch","description":"When a mismatch occurs with border length already zero, resolve the current LPS slot to 0 and advance the scan index.","commonMistakes":["Retrying forever when length is already zero","Advancing after overwriting the zero LPS value with a nonzero value"],"hint":"With no shorter border to fall back to, the current position is resolved as 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"string-matching","fact":"builds_prefix_function_table","scope":"zero-border-mismatch","readMode":"string-matching-value-query-v1"}]},"semanticSpec":{"intent":"Handle the mismatch branch when no candidate border remains.","doneWhen":"This step is done when a mismatch at length 0 records or preserves lps[i] = 0 and advances i to the next position.","shouldFailWhen":"This step should fail if the scan gets stuck at the same index, falls back below zero, or leaves the LPS slot unresolved.","roles":["current index","zero border length","LPS slot","scan advance"],"mustProve":["The branch detects mismatch with border length 0.","The current LPS entry is resolved as 0.","The scan advances to the next index."],"mustNotAccept":["Retrying the same comparison forever.","Changing length to a negative value."],"equivalentVariants":["Explicitly write 0 then increment i.","Rely on zero-initialized LPS storage while still advancing i."],"proofSnippets":[{"id":"py-build-kmp-prefix-zero-border-mismatch","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]\n        else:\n            lps[i] = 0\n            i += 1"}]}},{"id":"return-table","title":"Return the table","description":"Return the completed LPS table.","commonMistakes":["Returning the final border length instead of the table","Returning the input pattern"],"hint":"The caller needs every table slot, not only the last one.","semanticSpec":{"intent":"Return the populated prefix-function table.","doneWhen":"The solution returns the LPS table after the prefix scan completes.","shouldFailWhen":"This step should fail if the terminal return is not the result sequence.","roles":["LPS table","terminal return"],"mustProve":["The indexed result sequence is returned."],"mustNotAccept":["Returning only the scalar border length."],"proofSnippets":[{"id":"py-build-kmp-prefix-return-table","language":"python","code":"def buildPrefixTable(pattern: str) -> list[int]:\n    lps = [0] * len(pattern)\n    length = 0\n    i = 1\n    while i < len(pattern):\n        if pattern[i] == pattern[length]:\n            length += 1\n            lps[i] = length\n            i += 1\n        elif length != 0:\n            length = lps[length - 1]\n        else:\n            lps[i] = 0\n            i += 1\n    return lps"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_result_sequence","scope":"return-result","readMode":"array-scan-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Carry one border length through the scan: extend it on a match, fall back through lps on a mismatch, and never recompare what is already confirmed, turning the O(n cubed) recheck into a single O(n) pass.","workspacePanel":"code","body":["The leap from rechecking every prefix to one moving border is reuse: the length already proved at the last position tells the next one where to start instead of restarting the search.","The fallback is what makes that safe. Shrinking to lps[length - 1] lands on the next prefix still guaranteed to match, so the scan revises the border without ever walking backward."],"takeaways":[{"title":"One length is the whole state","body":"The longest confirmed border length carries all the progress the next position needs, so each character either extends it or shrinks it."},{"title":"Fall back, do not restart","body":"A broken border drops to lps[length - 1], the border of the part that did match, recovering shorter matches a reset to 0 would throw away."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
