Bird
Raised Fist0
DSA Goprogramming~10 mins

String Pattern Matching Naive in DSA Go - Execution Trace

Choose your learning style10 modes available
Concept Flow - String Pattern Matching Naive
Start at text index i=0
↓
Compare pattern with text from i
↓
Match all pattern chars?
Yes→Pattern found at i
No↓
Increment i by 1
↓
Check if i <= text length - pattern length
↓
Stop search
Start comparing the pattern at each position in the text until the pattern matches or the text ends.
Execution Sample
DSA Go
text := "abcxabcdabxabcdabcdabcy"
pattern := "abcdabcy"
for i := 0; i <= len(text)-len(pattern); i++ {
  match := true
  for j := 0; j < len(pattern); j++ {
    if text[i+j] != pattern[j] { match = false; break }
  }
  if match { fmt.Println("Pattern found at index", i) }
}
This code checks each position in the text to see if the pattern matches starting there.
Execution Table
StepOperationText Index iPattern Index jCharacter CompareMatch So FarActionOutput
1Start outer loop0--trueStart comparing pattern at i=0-
2Compare chars00'a' == 'a'trueContinue-
3Compare chars01'b' == 'b'trueContinue-
4Compare chars02'c' == 'c'trueContinue-
5Compare chars03'x' == 'd'falseMismatch, break inner loop-
6Increment i1---Try next position i=1-
7Start outer loop1--trueStart comparing pattern at i=1-
8Compare chars10'b' == 'a'falseMismatch, break inner loop-
9Increment i2---Try next position i=2-
10Start outer loop2--trueStart comparing pattern at i=2-
11Compare chars20'c' == 'a'falseMismatch, break inner loop-
12Increment i3---Try next position i=3-
13Start outer loop3--trueStart comparing pattern at i=3-
14Compare chars30'x' == 'a'falseMismatch, break inner loop-
15Increment i4---Try next position i=4-
16Start outer loop4--trueStart comparing pattern at i=4-
17Compare chars40'a' == 'a'trueContinue-
18Compare chars41'b' == 'b'trueContinue-
19Compare chars42'c' == 'c'trueContinue-
20Compare chars43'd' == 'd'trueContinue-
21Compare chars44'a' == 'a'trueContinue-
22Compare chars45'b' == 'b'trueContinue-
23Compare chars46'x' == 'c'falseMismatch, break inner loop-
24Increment i5---Try next position i=5-
25Start outer loop5--trueStart comparing pattern at i=5-
26Compare chars50'b' == 'a'falseMismatch, break inner loop-
27Increment i6---Try next position i=6-
28Start outer loop6--trueStart comparing pattern at i=6-
29Compare chars60'c' == 'a'falseMismatch, break inner loop-
30Increment i7---Try next position i=7-
31Start outer loop7--trueStart comparing pattern at i=7-
32Compare chars70'd' == 'a'falseMismatch, break inner loop-
33Increment i8---Try next position i=8-
34Start outer loop8--trueStart comparing pattern at i=8-
35Compare chars80'a' == 'a'trueContinue-
36Compare chars81'b' == 'b'trueContinue-
37Compare chars82'x' == 'c'falseMismatch, break inner loop-
38Increment i9---Try next position i=9-
39Start outer loop9--trueStart comparing pattern at i=9-
40Compare chars90'b' == 'a'falseMismatch, break inner loop-
41Increment i10---Try next position i=10-
42Start outer loop10--trueStart comparing pattern at i=10-
43Compare chars100'x' == 'a'falseMismatch, break inner loop-
44Increment i11---Try next position i=11-
45Start outer loop11--trueStart comparing pattern at i=11-
46Compare chars110'a' == 'a'trueContinue-
47Compare chars111'b' == 'b'trueContinue-
48Compare chars112'c' == 'c'trueContinue-
49Compare chars113'd' == 'd'trueContinue-
50Compare chars114'a' == 'a'trueContinue-
51Compare chars115'b' == 'b'trueContinue-
52Compare chars116'c' == 'c'trueContinue-
53Compare chars117'y' == 'y'truePattern matched fullyPattern found at index 11
54Increment i12---Try next position i=12-
55Start outer loop12--trueStart comparing pattern at i=12-
56Compare chars120'b' == 'a'falseMismatch, break inner loop-
57Increment i13---Try next position i=13-
58Start outer loop13--trueStart comparing pattern at i=13-
59Compare chars130'c' == 'a'falseMismatch, break inner loop-
60Increment i14---Try next position i=14-
61Start outer loop14--trueStart comparing pattern at i=14-
62Compare chars140'd' == 'a'falseMismatch, break inner loop-
63Increment i15---Try next position i=15-
64Start outer loop15--trueStart comparing pattern at i=15-
65Compare chars150'a' == 'a'trueContinue-
66Compare chars151'b' == 'b'trueContinue-
67Compare chars152'c' == 'c'trueContinue-
68Compare chars153'd' == 'd'trueContinue-
69Compare chars154'a' == 'a'trueContinue-
70Compare chars155'b' == 'b'trueContinue-
71Compare chars156'c' == 'c'trueContinue-
72Compare chars157'y' == 'y'truePattern matched fullyPattern found at index 15
73Increment i16---Try next position i=16-
74Check loop condition16---i > len(text)-len(pattern), stop-
💡 i reaches 16, condition 16 <= 24-8 is False, search ends
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7After 8After 9After 10After 11After 12After 13After 14After 15After 16Final
i01234567891011121314151616
j-311000020070007--
matchtruefalsefalsefalsetruefalsefalsefalsefalsefalsefalsetruefalsefalsefalsetrue--
Key Moments - 3 Insights
Why does the inner loop break early when a mismatch is found?
Because once a character doesn't match, continuing to check the rest of the pattern is pointless. This is shown in execution_table rows like 5 and 23 where 'match' becomes false and the inner loop breaks.
Why does the outer loop stop when i > len(text) - len(pattern)?
Because starting the pattern beyond that point means the pattern would not fit entirely in the remaining text. This is shown in the exit_note and row 74 where the loop condition fails.
What does 'match' variable represent during execution?
'match' tracks if all characters matched so far at the current position i. If any mismatch occurs, it becomes false and the inner loop breaks, as seen in variable_tracker and execution_table rows.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 23. What is the value of 'match' after comparing text[4+6] and pattern[6]?
Atrue
Bfalse
Cundefined
Dtrue but breaks anyway
💡 Hint
Check the 'Match So Far' column at step 23 in execution_table.
At which value of i does the pattern first fully match the text?
A11
B4
C15
D0
💡 Hint
Look for 'Pattern found at index' output in execution_table rows.
If the pattern length was shorter, how would the number of outer loop iterations change?
AFewer iterations
BNo change
CMore iterations
DInfinite loop
💡 Hint
Refer to the exit condition i <= len(text) - len(pattern) in concept_flow and exit_note.
Concept Snapshot
Naive String Pattern Matching:
- Check pattern at each text index i
- Compare characters one by one
- If mismatch, move to next i
- Stop when i > text length - pattern length
- Prints all match positions
Full Transcript
This visualization shows how the naive string pattern matching algorithm works by checking each position in the text to see if the pattern matches starting there. The outer loop moves the starting index i from 0 up to the point where the pattern can still fit. The inner loop compares each character of the pattern with the corresponding character in the text. If any character mismatches, the inner loop breaks early and the outer loop increments i to try the next position. When all characters match, the pattern is found and the index is printed. The process continues until no more positions remain to check. Variables i, j, and match track the current indices and matching status. The execution table shows each comparison step, the match status, and actions taken. Key moments clarify why the inner loop breaks early, why the outer loop stops at a certain point, and what the match variable means. The quiz tests understanding of match status, first match position, and effect of pattern length on iterations.

Practice

(1/5)
1. What is the main idea behind the naive string pattern matching algorithm?
easy
A. Check every possible position in the text for the pattern
B. Use a hash function to find the pattern quickly
C. Preprocess the pattern to skip some comparisons
D. Sort the text and pattern before matching

Solution

  1. Step 1: Understand naive matching approach

    The naive algorithm tries to match the pattern starting at each position in the text one by one.
  2. Step 2: Compare with other methods

    Other methods like hashing or preprocessing are not part of the naive approach.
  3. Final Answer:

    Check every possible position in the text for the pattern -> Option A
  4. Quick Check:

    Naive = Check all positions [OK]
Hint: Naive means try all positions one by one [OK]
Common Mistakes:
  • Thinking naive uses hashing
  • Assuming pattern preprocessing is done
  • Believing text is sorted first
2. Which of the following Go code snippets correctly starts the outer loop for naive string pattern matching?
easy
A. for i := 0; i <= len(text)-len(pattern); i++ {
B. for i := 0; i < len(text); i++ {
C. for i := 1; i <= len(text); i++ {
D. for i := 0; i < len(pattern); i++ {

Solution

  1. Step 1: Determine loop range for matching

    The outer loop must run from 0 to len(text)-len(pattern) to avoid out-of-range errors.
  2. Step 2: Check each option

    for i := 0; i <= len(text)-len(pattern); i++ { correctly uses i <= len(text)-len(pattern). Others either go too far or use wrong limits.
  3. Final Answer:

    for i := 0; i <= len(text)-len(pattern); i++ { -> Option A
  4. Quick Check:

    Loop till text length minus pattern length [OK]
Hint: Loop till text length minus pattern length [OK]
Common Mistakes:
  • Looping beyond valid start positions
  • Starting loop from 1 instead of 0
  • Using pattern length as loop limit
3. What will be the output of the following Go code snippet?
text := "banana"
pattern := "ana"
count := 0
for i := 0; i <= len(text)-len(pattern); i++ {
  j := 0
  for j < len(pattern) && text[i+j] == pattern[j] {
    j++
  }
  if j == len(pattern) {
    count++
  }
}
fmt.Println(count)
medium
A. 1
B. 3
C. 0
D. 2

Solution

  1. Step 1: Identify pattern matches in text

    Check each position in "banana" for "ana": positions 1-3 and 3-5 match.
  2. Step 2: Count matches

    Two matches found, so count is 2.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    "ana" appears twice in "banana" [OK]
Hint: Count all exact matches sliding over text [OK]
Common Mistakes:
  • Counting overlapping matches incorrectly
  • Off-by-one errors in loop limits
  • Assuming only first match counts
4. The following Go code tries to count pattern occurrences but has a bug. What is the bug?
text := "abcabcabc"
pattern := "abc"
count := 0
for i := 0; i < len(text)-len(pattern); i++ {
  j := 0
  for j < len(pattern) && text[i+j] == pattern[j] {
    j++
  }
  if j == len(pattern) {
    count++
  }
}
fmt.Println(count)
medium
A. The inner loop condition is wrong
B. The outer loop should use <= instead of <
C. The count variable is not initialized
D. The pattern length is not checked

Solution

  1. Step 1: Analyze outer loop range

    The loop runs from 0 to len(text)-len(pattern)-1, missing last valid start index.
  2. Step 2: Correct loop condition

    Changing < to <= includes last position, fixing missed matches.
  3. Final Answer:

    The outer loop should use <= instead of < -> Option B
  4. Quick Check:

    Loop must cover last valid start index [OK]
Hint: Use <= to include last possible start index [OK]
Common Mistakes:
  • Using < instead of <= in outer loop
  • Ignoring last possible match position
  • Misunderstanding loop boundaries
5. Given the text "abracadabra" and pattern "abra", how many times will the naive algorithm find the pattern if overlapping matches are counted? Use the naive approach code below:
text := "abracadabra"
pattern := "abra"
count := 0
for i := 0; i <= len(text)-len(pattern); i++ {
  j := 0
  for j < len(pattern) && text[i+j] == pattern[j] {
    j++
  }
  if j == len(pattern) {
    count++
  }
}
fmt.Println(count)
hard
A. 3
B. 1
C. 2
D. 4

Solution

  1. Step 1: Identify all pattern matches including overlaps

    "abra" appears at positions 0-3 and 7-10 in "abracadabra".
  2. Step 2: Count total matches

    Two matches found, so count is 2.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    "abra" occurs twice overlapping allowed [OK]
Hint: Check all positions including overlaps [OK]
Common Mistakes:
  • Counting only first match
  • Missing second overlapping match
  • Confusing substring positions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard