String algorithms
Алгоритмы на строках
These are methods for working with sequences of characters, such as finding a piece of text, checking whether a word reads the same backward, or measuring how similar two strings are.
Also known as: KMP, palindrome
Start with the kind of match you need
String algorithms work on ordered sequences. The same input can lead to very different problems: find a literal phrase, find the longest stretch with no repeated characters, or count the edits needed to turn one word into another. One distinction matters right away: a substring must be contiguous. In cart, ar is a substring, whereas ct is a subsequence that skips the middle letters.
Exact search: from a simple scan to KMP
Suppose a text has length n and a nonempty pattern has length m, with m ≤ n. A straightforward search tries each possible starting position and compares characters until it finds a mismatch or a full match. That can take O((n − m + 1) · m) comparisons in the worst case. A long run of a characters and a pattern that contains many as followed by b illustrate why: almost the same comparison happens at each position.
Knuth–Morris–Pratt (KMP) avoids starting over. For each prefix of the pattern, it precomputes the length of the longest shorter prefix that is also a suffix of that fragment. For example, abab starts and ends with ab. If the matcher has just read abab and the next character doesn't match, it can keep the trailing ab as a partial match instead of reading those characters again. Preprocessing and searching take O(n + m) time and O(m) auxiliary space, excluding the output.
A different problem: checking a palindrome
A palindrome reads the same in both directions. To check the whole string, compare the first and last characters, then move both indices inward. A mismatch settles the question immediately.
def is_palindrome(text: str) -> bool:
left, right = 0, len(text) - 1
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
return True
This accepts level and noon in O(n) time and O(1) extra space. Finding the longest palindrome inside a string is a different task. Expanding around every center is one option; remember to try gaps between characters as well as characters themselves. Otherwise you'll miss even-length palindromes such as noon.
In production and in interviews
For an exact lookup in a document or a log entry, start with the language's built-in substring search. Other requirements call for other tools: a trie is useful for prefix-based autocomplete, while edit distance can score candidates for a spelling correction. For human-facing text, define what counts as equal. For instance, é can be represented as one Unicode code point or as e followed by a combining accent; an exact comparison need not treat those representations as equal.
In an interview, pin down the return value before writing code. Does the caller want the first match or every match? Should searching for aa in aaa return both starts? What happens with an empty pattern? Then state what n and m measure and explain why your method does or doesn't revisit input.