Definition
Brute-force Algorithm (String Matching)
Given a text and a pattern , the brute-force algorithm for the string matching problem tests every possible starting position. At each position, it compares pattern characters with text characters from left to right until a mismatch occurs or the whole pattern matches. It returns
After each test, the starting position advances by one, so overlapping occurrences are retained. If , there are no occurrences. The empty string occurs at all boundaries of the text.
Pseudocode
Indices are one-based. An integer range is empty when its upper bound is smaller than its lower bound.
string_matching_bruteforce(T, P):
n := |T|
m := |P|
occurrences := []
for i := 1 to n - m + 1:
j := 1
while j <= m and T[i + j - 1] == P[j]:
j := j + 1
if j == m + 1:
append i to occurrences
return occurrencesThe and condition short-circuits: no character is accessed once j > m. Thus an empty pattern is accepted at every boundary without a character comparison.
Correctness
Exact Occurrence Positions
The algorithm returns every occurrence of in , and no other position.
Proof
At the start of each inner-loop iteration, the first pattern characters match the text at the current alignment:
This holds initially because no characters have been compared. Each successful comparison extends the matching prefix by one character.
No false positives: a position is appended only when , so all characters match.
No missed occurrences: the outer loop visits every valid starting position. At an actual occurrence, every comparison succeeds, so the position is appended. A mismatch rejects only the current alignment.
For , the outer loop is empty. For , the matching condition is vacuous, so all boundaries are returned.
Complexity
For , there are alignments and at most character comparisons per alignment. The worst-case time complexity is
which is . The bound is attained by and : every alignment requires all comparisons. Unlike the exponential enumeration for longest common subsequence, this algorithm enumerates only contiguous starting positions.
If , the running time is . If , returning all boundaries takes time.
Auxiliary space is , excluding the output list, which stores occurrence positions in space.
Examples
Overlapping occurrences
Let and .
- At , all three characters match: append .
- At , the first comparison fails because .
- At , all three characters match: append .
The result is . Advancing by one rather than by the pattern length preserves the overlapping occurrence at position .