Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
strs = ["flower","flow","flight"]"fl"strs = ["dog","racecar","car"]""prefix = strs[0] (candidate starts as the first string)i = 1 to n−1: check strs[i].startsWith(prefix)strs[i] does not start with prefix: trim one char from the rightprefix becomes empty → return "" immediatelyprefixHorizontal scanning treats strs[0] as the candidate prefix. The prefix can only shrink — it is trimmed from the right until it matches each subsequent string. Once trimmed to match all strings, it is the longest possible common prefix. S = total characters across all strings.
Building every possible prefix and checking it against every word is slow. And remember, the prefix can never be longer than the shortest word.
Line the words up, one under another, and read them column by column. Take the letter from the first word, and check that every other word has the same letter in that column. Stop at the first mismatch, or as soon as a word runs out.
Compare column by column, and stop at the first mismatch. The prefix is never longer than the shortest word.
Run the animation above on your own input, or watch the 1:20 video explanation of Longest Common Prefix with a dry run and Java code.