Longest Common Prefix of Strings
A longest common prefix stops where any supplied string ends or the next code points disagree.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace three names
For "station", "stack", and "staff", the common prefix is "sta". At position three, the compared code points differ. Visit positions in increasing order with zero-based indexing, and stop at the first disagreement.
Check early termination
Adding the string "st" reduces the answer to "st" before any differing position needs inspection. A list with no names requires a stated convention, such as returning empty text. Function preconditions define whether that input is allowed.[1]
Justify why the first mismatch ends the search
In ["stamp", "stand", "stack"], every word starts with "sta". At the next position m and n disagree with c, so any longer prefix fails. Use the shortest string length as a bound before indexing every word. If an input equals the entire common prefix, it supplies the stopping condition even when no characters disagree. Test ["turn", "tur", "turbo"] for that boundary. See prefix and suffix matches.
Specify the zero-input case and the comparison unit
A list containing an empty string has empty shared prefix. A list with zero inputs can also return empty by convention, although there is no shortest input to bound the answer. For user-facing text, a prefix ending between a base character and its combining mark can display oddly. Consider normalization and the appropriate text unit before exposing a boundary to users. See Unicode positions.