Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The String Matching proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Specify first or all occurrences, overlap, empty patterns and symbol equality before selecting a matcher. Contrast naive alignment scans, deterministic KMP reuse, and verified rolling-hash candidates.
1 practice exercise1 interview problem
Recognize it when The pattern must match consecutive symbols at some text alignment.
Checking your account…
String matching asks where a pattern aligns with consecutive text symbols. Define first versus all matches, overlapping behavior, case normalization, and the empty-pattern result before selecting an algorithm.
Naive matching advances one alignment and repeats comparisons. KMP reuses a prefix-suffix table, while Rabin-Karp reuses a rolling fingerprint and verifies candidates.
def alignment_trace(text,pattern):
if pattern=="":return [[0,0]]
trace=[]
for start in range(len(text)-len(pattern)+1):
matched=0
while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1
trace.append([start,matched])
if matched==len(pattern):break
return traceImplement alignment_trace(text,pattern). Return [start,matched_prefix_length] for each alignment through the first full match. Empty pattern returns [[0,0]]; a pattern longer than text returns [].
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def alignment_trace(text,pattern):
if pattern=="":return [[0,0]]
trace=[]
for start in range(len(text)-len(pattern)+1):
matched=0
while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1
trace.append([start,matched])
if matched==len(pattern):break
return tracePredict the matched-prefix length at each legal start in the existing Lab. It intentionally stops after the first full match, so the trace is not an all-occurrence output.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Reset start zero | matched=0 |
start=0, matched=0 |
Each naive alignment restarts its prefix comparison. |
| Compare at zero | while matched<len(pattern) and text[start+matched]==pattern[matched]:matched+=1 |
after inner loop: matched=1 |
The first a agrees, then the next a mismatches pattern b. |
| Record zero | trace.append([start,matched]) |
trace=[[0,1]] |
Recording happens after the comparison loop, not on every matched symbol. |
| Record start one | trace.append([start,matched]) |
after its reset and comparison loop: trace=[[0,1],[1,1]] |
The next alignment repeats one a comparison before c mismatches b. |
| Record start two | trace.append([start,matched]) |
after its reset and comparison loop: row=[2,0] |
c rejects this alignment on its first comparison. |
| Record complete alignment | trace.append([start,matched]) |
after start 3 comparison loop: row=[3,3] |
The inner loop has matched every pattern symbol before the row is recorded. |
| Stop at first match | if matched==len(pattern):break |
trace has four rows and scanning stops |
This Lab returns the first completed alignment trace, not every occurrence. |
| Empty pattern | if pattern=="":return [[0,0]] |
[[0,0]] |
The explicit empty boundary is returned before alignment scanning. |
| Output | |
|---|---|
print(alignment_trace("aacaba","aba")) |
[[0, 1], [1, 1], [2, 0], [3, 3]] |
print(alignment_trace("abc","")) |
[[0, 0]] |
Use the two lengths to explain cost, then choose the method. A linear KMP guarantee and a verified rolling-hash candidate check solve different repeated-work problems.
Choose direct comparison for short inputs, KMP for deterministic linear worst-case matching, rolling hash for many same-length windows, or an automaton/trie for multiple patterns.
def find_pattern(text,pattern):
if pattern=="":return 0
for start in range(len(text)-len(pattern)+1):
if all(text[start+offset]==character for offset,character in enumerate(pattern)):return start
return -1Implement find_pattern(text,pattern). Return the first start index or -1, with empty pattern at zero.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def find_pattern(text,pattern):
if pattern=="":return 0
for start in range(len(text)-len(pattern)+1):
if all(text[start+offset]==character for offset,character in enumerate(pattern)):return start
return -1Common search APIs define the empty pattern at index zero. Python string indexes count Unicode code points, not grapheme clusters; normalization may be needed when visually equivalent text must match.
Say: “An alignment begins at this text index. On mismatch, this algorithm reuses this precise prior information instead of restarting blindly.” State empty behavior, overlap policy, alphabet assumptions, and complexity in text and pattern lengths.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The String Matching proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Naive alignment scan | O((n-m+1)*max(1,m)) when m<=n | O((n-m+1)*max(1,m)) when m<=n | Constant-cost character equality; oversized patterns have no starts. |
| KMP search with prefix table | O(n+m) | O(n+m) | Plus returned match indexes. |
| Verified rolling-hash matching | O(n+m+C*m) | O(n * max(1,m) + m) | C is the number of hash candidates, including real matches; verification can dominate. Empty patterns return n+1 boundaries in the all-match interface, costing O(n+1). |
Naive first-match scan O(1) extra state; its alignment trace O(n); KMP prefix table O(m).
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
For text abc and pattern bc, start 1 is legal. range(n-m) excludes it.
Prevent it: Include n-m by using range(n-m+1).
starts=list(range(len(text)-len(pattern)))starts=list(range(len(text)-len(pattern)+1))Where you will hit this: Find Every String Match(opens in a new tab)
In aaaa, width-2 matches start at 0,1,2. Jumping by width after a match skips the middle one.
Prevent it: Advance one start for naive all-match enumeration, or use a proven prefix fallback.
next_start=start+len(pattern)next_start=start+1Where you will hit this: Find Every String Match(opens in a new tab)
The first-occurrence contract places an empty pattern at zero, even in empty text.
Prevent it: Handle the documented empty-pattern result explicitly.
answer=-1answer=0 if pattern=="" else -1Where you will hit this: Lowest Common Ancestor in a BST(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27