Easy · Prefix Walk
Understand → Visualise → Practice.
In a trie, a common prefix continues while the current node has exactly one child and is not the end of a word. The same idea can be implemented directly with strings.
Shrink a candidate prefix until every word starts with it.
Use the first word as the candidate.
Shorten while the next word does not match.
The remaining prefix is shared by all words.
O(S) time for S total input characters and O(1) extra space beyond the prefix.
Stop at the end of the shortest word; a prefix cannot be longer than it.
Read the full guide first: Tries and Prefix Search.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.