Pattern visualizer
Longest Common Prefix
The common prefix of all the words can only shrink as you check more words, never grow — so start by assuming the whole first word is the answer, then test that candidate against each other word in turn and chop characters off the end whenever it doesn't fit. Once the candidate is a genuine prefix of every word checked so far, whatever survives to the end is the longest common prefix. Animated on: Given words=["flower","flow","flight"], find the longest common prefix.
Shrink the candidate prefix word by word
Start with words=["flower","flow","flight"]. Set prefix = strs[0] = "flower".
1FUNCTION longestCommonPrefix(strs):2 IF strs is empty: RETURN ''3 prefix = strs[0]4 FOR each i from 1 to the length of strs:5 WHILE prefix is not a prefix of strs[i]:6 drop the last character of prefix7 IF prefix is now empty: RETURN ''8 END WHILE9 END FOR10 RETURN prefix11END FUNCTION
← / → step · space play · Home restart