Find the Longest Common Prefix of a set of words using a Trie. Walk the single-branch path until a branch or word-end is reached.
About this algorithm
The longest common prefix (LCP) of a set of words is the longest string that every one of them starts with. Put all the words into a trie and the common prefix is the stretch of path from the root that never branches: follow it while each node has exactly one child and no word ends there.
Use the trie method when the words are already in a trie, or when you will ask prefix questions about the same words many times, for example grouping URLs or file paths by their shared start. For a one-off question on a plain list, the simpler answers to LeetCode 14 do better: compare the words column by column, or sort the list and compare only its first and last words, neither of which builds anything. The autocomplete page uses the same kind of trie for the opposite job: it starts from a prefix you give it and gathers the words below, while this page finds the prefix the words already share.
Build the trie: one node per character, words that begin alike share their first nodes, and the node where each word finishes is marked as a word end.
Begin with an empty prefix at the root.
If the current node has exactly one child and is not a word end, append that child's letter to the prefix and move down to it.
Two or more children mean the words disagree on the next letter. A word end means one word is used up, and no common prefix can be longer than that word; a node with no children is the same case. The letters collected so far are the answer.
The page's first preset inserts app, apple and apply. The root has one child, a, so the prefix becomes a; then p, giving ap; then p again, giving app. The node for app has one child, l, but it is marked as a word end, because app is itself one of the words. The walk stops and the answer is app. Without the word end check it would carry on to appl and report a prefix longer than the word app. The second preset, flower, flow and flight, stops after fl at a node with two children, o and i. The third, interview, interact and interest, collects inter and stops at a node with three children: v, a and e.
An empty string in the list marks the root itself as a word end, so the answer is empty straight away, which is correct. A list of one word returns the whole word. Words with no first letter in common leave the root with several children and an empty answer.
Time: building the trie touches each of the S characters across all the words once; the walk itself is only as long as the prefix, never longer than the shortest word. Space: when the words share little, the trie keeps close to one node per character, S nodes in all.