Ready — enter Text and Pattern to build the scene
Speed
🎨 Customize Colors
Scene Background
Block Color
Character Color
Match Color

🔎 Brute Force Match

Brute force string matching systematically checks if the pattern matches a substring at each position in the text. It aligns the pattern with the text and compares characters one by one. If a mismatch occurs, it shifts the pattern to the right by exactly one position and starts comparing again.

⏱ Best Case: O(n) ⏱ Average Case: O(n × m) ⏱ Worst Case: O(n × m) 💾 Space: O(1)
Python
def brute_force_match(text, pattern):
    n = len(text)
    m = len(pattern)

    for i in range(n - m + 1):
        j = 0
        while j < m:
            if text[i + j] != pattern[j]:
                break
            j += 1
            
        # Pattern matched completely
        if j == m:
            return i
            
    return -1
JavaScript
function bruteForceMatch(text, pattern) {
    const n = text.length;
    const m = pattern.length;
    
    for (let i = 0; i <= n - m; i++) {
        let j;
        for (j = 0; j < m; j++) {
            if (text[i + j] !== pattern[j]) {
                break;
            }
        }
        
        // Match found!
        if (j === m) {
            return i;
        }
    }
    
    return -1;
}