Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

String Pattern Matching Naive in DSA Javascript - 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→Record match at i
No↓
Increment i by 1
↓
Is i <= text length - pattern length?
Yes→Repeat compare
No↓
End
Start from the beginning of the text, compare the pattern character by character. If all match, record the position. Move one step forward and repeat until the pattern cannot fit.
Execution Sample
DSA Javascript
function naiveSearch(text, pattern) {
  let matches = [];
  for (let i = 0; i <= text.length - pattern.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) {
      j++;
    }
    if (j === pattern.length) {
      matches.push(i);
    }
  }
  return matches;
}
This code searches for all occurrences of pattern in text using naive character-by-character matching.
Execution Table
StepOperationText Index iPattern Index jMatch CheckActionMatch Found Positions
1Start outer loop0--Compare pattern at text[0][]
2Compare chars00text[0] == pattern[0] ('a'=='a')Continue[]
3Compare chars01text[1] == pattern[1] ('b'=='b')Continue[]
4Compare chars02text[2] == pattern[2] ('c'=='c')Continue[]
5Compare chars03text[3] == pattern[3] ('d'=='d')Continue[]
6Compare chars04text[4] == pattern[4] ('a'=='a')Continue[]
7Compare chars05text[5] == pattern[5] ('b'=='b')Continue[]
8Compare chars06text[6] == pattern[6] ('c'=='c')Continue[]
9Compare chars07text[7] == pattern[7] ('d'=='d')Continue[]
10Compare chars08text[8] == pattern[8] ('a'=='a')Continue[]
11Compare chars09text[9] == pattern[9] ('b'=='b')Continue[]
12Compare chars010text[10] == pattern[10] ('c'=='c')Continue[]
13Compare chars011text[11] == pattern[11] ('d'=='d')Continue[]
14Pattern fully matched012j == pattern.length (12)Record match at i=0[0]
15Increment i1--Compare pattern at text[1][0]
16Compare chars10text[1] == pattern[0] ('b'=='a')Mismatch[0]
17Increment i2--Compare pattern at text[2][0]
18Compare chars20text[2] == pattern[0] ('c'=='a')Mismatch[0]
19Increment i3--Compare pattern at text[3][0]
20Compare chars30text[3] == pattern[0] ('d'=='a')Mismatch[0]
21Increment i4--Compare pattern at text[4][0]
22Compare chars40text[4] == pattern[0] ('a'=='a')Continue[0]
23Compare chars41text[5] == pattern[1] ('b'=='b')Continue[0]
24Compare chars42text[6] == pattern[2] ('c'=='c')Continue[0]
25Compare chars43text[7] == pattern[3] ('d'=='d')Continue[0]
26Compare chars44text[8] == pattern[4] ('a'=='a')Continue[0]
27Compare chars45text[9] == pattern[5] ('b'=='b')Continue[0]
28Compare chars46text[10] == pattern[6] ('c'=='c')Continue[0]
29Compare chars47text[11] == pattern[7] ('d'=='d')Continue[0]
30Pattern fully matched412j == pattern.length (12)Record match at i=4[0,4]
31Increment i5--Compare pattern at text[5][0,4]
32Compare chars50text[5] == pattern[0] ('b'=='a')Mismatch[0,4]
33Increment i6--Compare pattern at text[6][0,4]
34Compare chars60text[6] == pattern[0] ('c'=='a')Mismatch[0,4]
35Increment i7--Compare pattern at text[7][0,4]
36Compare chars70text[7] == pattern[0] ('d'=='a')Mismatch[0,4]
37Increment i8--Compare pattern at text[8][0,4]
38Compare chars80text[8] == pattern[0] ('a'=='a')Continue[0,4]
39Compare chars81text[9] == pattern[1] ('b'=='b')Continue[0,4]
40Compare chars82text[10] == pattern[2] ('c'=='c')Continue[0,4]
41Compare chars83text[11] == pattern[3] ('d'=='d')Continue[0,4]
42Pattern fully matched812j == pattern.length (12)Record match at i=8[0,4,8]
43Increment i9--Compare pattern at text[9][0,4,8]
44Check loop condition9-9 <= 20 - 12 (8)?False[0,4,8]
💡 i reached 9 which is greater than text length - pattern length, so loop ends
Variable Tracker
VariableStartAfter Step 14After Step 30After Step 42Final
i00489 (loop ends)
j-12 (pattern matched)12 (pattern matched)12 (pattern matched)-
Match Found Positions[][0][0,4][0,4,8][0,4,8]
Key Moments - 3 Insights
Why do we stop comparing characters as soon as one mismatch is found?
Because the pattern cannot match if any character differs. The execution_table rows 16, 18, 20 show immediate mismatch stops to save time.
Why does the outer loop run only until i <= text.length - pattern.length?
Because if i is greater, the pattern would not fit in the remaining text. See execution_table row 44 where loop ends due to this condition.
Why do we increment i by 1 each time instead of skipping more?
Naive search checks every position for possible match. It does not skip ahead. This is shown in variable_tracker where i increments by 1 each time.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 14, what does the algorithm record?
AA mismatch at text index 0
BIncrement i to 1
CA match found starting at text index 0
DPattern length is less than text length
💡 Hint
Check the 'Action' and 'Match Found Positions' columns at step 14
At which step does the outer loop condition become false and stop the search?
AStep 42
BStep 44
CStep 30
DStep 16
💡 Hint
Look at the 'Check loop condition' operation and the exit_note
If the pattern was shorter, how would the number of outer loop iterations change?
AMore iterations because pattern fits more times
BFewer iterations because pattern fits less times
CNo change in iterations
DOuter loop would not run
💡 Hint
Refer to variable_tracker 'i' max value depends on text.length - pattern.length
Concept Snapshot
Naive String Pattern Matching:
- Start at text index i=0
- Compare pattern chars one by one
- If all match, record i
- Increment i by 1
- Stop when pattern can't fit
- Simple but slow for large texts
Full Transcript
The naive string pattern matching algorithm checks every possible position in the text where the pattern could fit. It compares each character of the pattern with the corresponding character in the text. If all characters match, it records the starting index. If a mismatch occurs, it moves to the next position in the text and repeats. The process stops when the pattern cannot fit in the remaining text. This method is straightforward but can be slow for large inputs.

Practice

(1/5)
1. What does the naive string pattern matching algorithm do?
easy
A. It checks every possible position in the text to find the pattern.
B. It uses a hash function to find the pattern quickly.
C. It sorts the text before searching for the pattern.
D. It uses a tree structure to match the pattern.

Solution

  1. Step 1: Understand naive pattern matching

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

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

    It checks every possible position in the text to find the pattern. -> Option A
  4. Quick Check:

    Naive = Check all positions [OK]
Hint: Naive means try all positions one by one [OK]
Common Mistakes:
  • Confusing naive with hashing or advanced algorithms
  • Thinking naive sorts the text
  • Assuming naive uses data structures like trees
2. Which of the following is the correct syntax to start a loop for naive pattern matching in JavaScript?
for (___; i <= text.length - pattern.length; i++)
easy
A. const i = 0
B. var i = 1
C. let i = 0
D. i = 0

Solution

  1. Step 1: Identify loop initialization

    The loop variable must start at 0 to check from the beginning of the text.
  2. Step 2: Choose correct declaration

    Using 'let' is correct for block scope and allows incrementing i.
  3. Final Answer:

    let i = 0 -> Option C
  4. Quick Check:

    Loop start = let i = 0 [OK]
Hint: Use 'let' to declare loop variable starting at zero [OK]
Common Mistakes:
  • Using 'const' which cannot be incremented
  • Starting loop at 1 instead of 0
  • Not declaring variable with let or var
3. What will be the output of the following code?
function naiveSearch(text, pattern) {
  let count = 0;
  for (let i = 0; i <= text.length - pattern.length; i++) {
    let j;
    for (j = 0; j < pattern.length; j++) {
      if (text[i + j] !== pattern[j]) break;
    }
    if (j === pattern.length) count++;
  }
  return count;
}

console.log(naiveSearch('abababa', 'aba'));
medium
A. 3
B. 2
C. 1
D. 0

Solution

  1. Step 1: Check all pattern matches in text

    Positions checked: 0,1,2,3,4. Matches at 0 ('aba'), 2 ('aba'), and 4 ('aba').
  2. Step 2: Count total matches

    There are 3 matches of 'aba' in 'abababa'.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Count matches = 3 [OK]
Hint: Count overlapping matches carefully [OK]
Common Mistakes:
  • Missing overlapping matches
  • Counting only non-overlapping occurrences
  • Off-by-one errors in loop limits
4. Identify the error in this naive pattern matching code snippet:
function search(text, pattern) {
  for (let i = 0; i < text.length; i++) {
    let j = 0;
    while (j < pattern.length && text[i + j] === pattern[j]) {
      j++;
    }
    if (j === pattern.length) return i;
  }
  return -1;
}
medium
A. j should be declared with var instead of let
B. Loop condition should be i <= text.length - pattern.length
C. Return -1 should be inside the for loop
D. While loop condition should use || instead of &&

Solution

  1. Step 1: Analyze loop range

    The outer loop runs till i < text.length, which can cause out-of-bound access when i + j exceeds text length.
  2. Step 2: Correct loop condition

    It should be i <= text.length - pattern.length to avoid overflow.
  3. Final Answer:

    Loop condition should be i <= text.length - pattern.length -> Option B
  4. Quick Check:

    Loop limit fix = i <= text.length - pattern.length [OK]
Hint: Limit loop to avoid index overflow [OK]
Common Mistakes:
  • Ignoring index overflow causing runtime errors
  • Misplacing return statements
  • Wrong logical operators in conditions
5. Given a text and a pattern, how can you modify the naive pattern matching algorithm to count only non-overlapping occurrences of the pattern in the text?
hard
A. Use recursion to find matches
B. Use a hash function to skip characters
C. Sort the text before searching
D. After finding a match, increment the outer loop index by pattern length instead of 1

Solution

  1. Step 1: Understand overlapping vs non-overlapping

    Naive checks every position, counting overlapping matches. To avoid overlap, skip ahead after a match.
  2. Step 2: Modify loop increment

    When a match is found, increase the index by pattern length to jump past the matched substring.
  3. Final Answer:

    After finding a match, increment the outer loop index by pattern length instead of 1 -> Option D
  4. Quick Check:

    Skip matched length to avoid overlap [OK]
Hint: Jump by pattern length after match to avoid overlaps [OK]
Common Mistakes:
  • Trying to sort text which doesn't help
  • Using hashing which is unrelated here
  • Recursion adds complexity without solving overlap
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