Naive String Search Algorithm in TypeScript
Data Structures and Algorithms for Beginners
Photo by Lavi Perchik on Unsplash
The Naive String Search algorithm is a simple and straightforward approach to finding occurrences of a pattern (substring) within a larger text (string). It involves checking each possible position in the text for the presence of the pattern. While not the most efficient algorithm, it serves as a fundamental introduction to string searching.
Basic Implementation
function naiveStringSearch(text: string, pattern: string): number[] {
const occurrences: number[] = [];
for (let i = 0; i <= text.length - pattern.length; i++) {
let match = true;
for (let j = 0; j < pattern.length; j++) {
if (text[i + j] !== pattern[j]) {
match = false;
break;
}
}
if (match) {
occurrences.push(i);
}
}
return occurrences;
}
How Naive String Search Works
Iteration through Text
The algorithm iterates through each character in the text.
Comparison with Pattern
At each position in the text, it compares the characters with the characters in the pattern.
Pattern Match Check
If a match is found at a specific position, the algorithm records the starting index of the match.
Repeat
Repeat the process for each possible starting position in the text.
const text = "abracadabra";
const pattern = "abra";
const occurrences = naiveStringSearch(text, pattern);
console.log(occurrences); // Output: [0, 7]
Time Complexity
The time complexity of Naive String Search is O(m * n), where 'm' is the length of the text, and 'n' is the length of the pattern. In the worst case, the algorithm may need to check each character in the text for each possible starting position.
Space Complexity
The space complexity of Naive String Search is O(1), as it only requires a constant amount of additional memory for variables like occurrences.
When to Use Naive String Search
Naive String Search is suitable for small datasets or situations where a simple and easy-to-understand algorithm is sufficient. For larger datasets, more advanced string search algorithms like the Knuth-Morris-Pratt or Boyer-Moore algorithms are preferred due to their better time complexity.
Conclusion
While Naive String Search may not be the most efficient algorithm for large datasets, it provides a clear introduction to the basic principles of string searching. Understanding how it works is essential for building a foundation in algorithms and pattern matching.