Naive String Matching Algorithm

ABABDABACDABABCABAB

How Naive String Matching Works

The Naive String Matching algorithm is a simple and straightforward method for finding all occurrences of a pattern string within a larger text string.

The algorithm:

  1. Slide the pattern over the text one by one
  2. For each position, compare the characters of the pattern with the text
  3. If all characters match, we've found an occurrence of the pattern
  4. Move to the next position and repeat

While simple to implement, this algorithm has a time complexity of O(nm), where n is the length of the text and m is the length of the pattern. This can be inefficient for large texts or patterns.

function naiveStringMatch(text, pattern):
    n = length of text
    m = length of pattern
    
    for i from 0 to n - m:
        j = 0
        while j < m and text[i + j] == pattern[j]:
            j = j + 1
            visualize(text, pattern, i, j)
        if j == m:
            print "Pattern found at index", i

function visualize(text, pattern, i, j):
    // Update UI to show:
    // 1. The full text with the current window highlighted
    // 2. The pattern below the text, aligned with the current window
    // 3. Highlight matching characters
    // 4. Indicate the current comparison