Maintained by Vikas Dulgunde, software engineer
You are handed an array of strings and asked for the longest run of characters that appears at the very start of all of them. The match has to begin at index 0 and stay unbroken: as soon as one string disagrees with the others at some position, the common prefix stops there.
Think of it as lining the words up vertically and reading down each column. While every word has the same letter in a column, that letter belongs to the prefix. The first column where any two words differ, or where any word has already run out of characters, marks the end.
If the array holds a single string, that whole string is the answer, since it trivially agrees with itself. If any string is empty, or the very first characters already disagree, the answer is the empty string.
All three begin with 'f' then 'l'. At the third position 'o', 'o', and 'i' disagree, so the shared prefix is "fl".
The first characters are 'd', 'r', and 'c', which already differ, so there is no common prefix at all.
Every string shares "inter". The word "inter" ends right there, which caps the prefix at five characters even though the others continue.
Visible test cases
The answer can never be longer than the shortest string in the array, and it can never be longer than the first string either.
Try treating the first string as a candidate prefix, then shrink it as you compare it against each remaining string.
You can stop early the moment the candidate prefix becomes empty, since nothing later can revive it.
Walk character positions left to right across all strings at once. The first position where a string ends or a character disagrees is where the prefix stops.
Start with the first string as the full candidate prefix, then trim it against each next string until it fits all of them.