Substrings and Subsequences
A substring occupies contiguous positions. A subsequence preserves relative order while allowing gaps.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Use one short witness
In "abcdef", "bcd" is a substring from positions one through three. "bdf" is a subsequence because positions 1, 3, and 5 preserve order, but it skips c and e. A step in a slice provides one way to exhibit this particular subsequence.
Pick the intended rule
Searching for an exact tag fragment typically requires contiguity. Checking whether transaction A happened before C can allow B between them. Use membership semantics carefully, since ordinary Python string membership checks contiguous substrings.[1]
Write a witness as explicit positions
In "planet", the pattern "plt" is a subsequence at positions zero, one and five. It is absent as a substring because those positions are not contiguous. Conversely "lane" uses contiguous positions one through four, so it satisfies both definitions. Choose the relation that matches the task. A user searching for a quoted phrase may expect contiguity, while an ordered-event search may allow intervening symbols. See sequence slices.
Trace a greedy subsequence check
Scan the source left to right while holding the position of the next required pattern symbol. When a symbol matches, advance that pattern position. Taking the earliest match leaves the largest remaining suffix, so it cannot lose a solution relative to taking a later occurrence. Repeated symbols need distinct positions. Test a one-character source against a pattern requiring that character twice, as well as an empty pattern. See first-match scanning.