Searching text
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)String searching finds where a short pattern appears inside a larger body of text. We start with the straightforward sliding window comparison to see how text matching works and why repetitive inputs cause severe slowdowns.
The Sliding Pattern Search Approach
How do you check if a word appears inside a document? The simplest approach slides the pattern across the text one position at a time.
Example 1 · Naive search: O(N · M) time, O(1) space
import java.util.ArrayList;import java.util.List;
public class NaiveStringSearchDemo { public static List<Integer> search(String text, String pattern) { List<Integer> matches = new ArrayList<>(); int n = text.length(); int m = pattern.length();
for (int i = 0; i <= n - m; i++) { int j = 0; while (j < m && text.charAt(i + j) == pattern.charAt(j)) { j++; } if (j == m) { matches.add(i); } } return matches; }
public static void main(String[] args) { String text = "ABAAABCDABC"; String pattern = "ABC"; System.out.println("Matches found at indices: " + search(text, pattern)); }}Matches found at indices: [4, 8]
What this code does
- Loops through valid start indices from 0 to n - m.
- Compares characters until a mismatch or until all m characters match.
- Finds occurrences of 'ABC' at starting indices 4 and 8.
At each starting index i in the text, you compare pattern character j with text character i + j. If all characters match from j = 0 to M - 1, you have found the pattern at index i. If any character mismatches, you stop checking the current position immediately, slide the pattern one step forward to index i + 1, and restart comparing pattern characters from index 0.
Why Naive Search Can Be Disastrously Slow
On everyday English text, naive search runs surprisingly fast. In typical prose, a mismatch occurs almost immediately on the first or second character, meaning each starting position is checked in O(1) time on average.
Example 2 · Worst case of naive search: about N · M comparisons
public class NaiveWorstCaseDemo { public static int countComparisons(String text, String pattern) { int n = text.length(); int m = pattern.length(); int comparisons = 0;
for (int i = 0; i <= n - m; i++) { for (int j = 0; j < m; j++) { comparisons++; if (text.charAt(i + j) != pattern.charAt(j)) { break; } } } return comparisons; }
public static void main(String[] args) { String text = "AAAAAAA"; String pattern = "AAAB"; System.out.println("Text length: " + text.length()); System.out.println("Total comparisons: " + countComparisons(text, pattern)); }}Text length: 7 Total comparisons: 16
What this code does
- For n = 7 and m = 4, there are 7 - 4 + 1 = 4 starting positions.
- At each position, matches fail on the 4th character, making 4 comparisons each.
- Total comparisons: 4 positions * 4 comparisons = 16 operations.
However, consider searching for pattern 'AAAAAB' inside text 'AAAAAAAAAAAAAAAA'. At every single text position, naive search compares five 'A' characters successfully before failing on the sixth character 'B'. Because the algorithm re-scans the same text characters repeatedly, its worst-case time complexity degrades to O(N * M), where N is text length and M is pattern length. For a 1,000,000 character DNA sequence and a 10,000 character probe, naive search requires 10 billion comparisons!
Built-in Java Methods: indexOf and contains
Java provides built-in methods like text.indexOf(pattern) and text.contains(pattern). Under the hood, Java's standard library implements an optimized variant of sliding search.
Example 3 · Built-in indexOf and contains: O(N · M) worst case, O(1) space
public class JavaBuiltInSearchDemo { public static void main(String[] args) { String doc = "The quick brown fox jumps over the lazy dog"; System.out.println("Contains 'fox': " + doc.contains("fox")); System.out.println("Index of 'fox': " + doc.indexOf("fox")); System.out.println("Index of 'cat': " + doc.indexOf("cat")); System.out.println("Second 'the': " + doc.indexOf("the", 1)); }}Contains 'fox': true Index of 'fox': 16 Index of 'cat': -1 Second 'the': 31
What this code does
- contains returns true if the substring exists anywhere in the text.
- indexOf returns the 0-based start index of the first match, or -1 if not found.
- Overloaded indexOf(str, fromIndex) resumes searching from a specified offset.
Rather than checking every character in order, Java first scans quickly for the pattern's first character, often utilizing CPU vectorization (SIMD instructions) to locate candidate starting positions at hardware speed. While indexOf is fast and convenient for short strings and everyday documents, specialized algorithms are essential when searching genomic sequences, building high-throughput network filters, or processing large texts with repetitive alphabets.
Next step
Check your understanding
10 quick questions