Algorithmssubstring comparison
Substring Comparison (windows, slice equality)
TT
Testlaa Team
May 14, 2026•1 min read
Substring comparison checks if a slice equals another string—s[i:j] == pat or startswith/endswith for anchored checks. Rolling compare avoids rebuilding slices when you slide a window of fixed length.
Why this shows up in the real world
DNA k-mer scans compare each window to a motif. Search snippets bold the matching substring after compare.
Core idea (explained for students)
For every i, compare s[i : i + m] to pat—early break on first mismatch. Python slices copy—use character-wise loop if profiling shows allocation pressure (rare).
Try this in Python
def window_equals(s: str, i: int, pat: str) -> bool:
return s[i : i + len(pat)] == pat
print(window_equals("abcdef", 2, "cde"))
Common mistakes
- Off-by-one window end
i+m > n—loopi in range(n - m + 1). - Case sensitivity—normalize once if needed.
Key takeaways
- Reuse
m = len(pat)outside loops. - For many patterns against one text, consider Aho–Corasick when complexity demands it.
Tags:
StringsPythonStudents
