Longest common prefix
Scan column by column across every word at once. The prefix ends the moment one word disagrees.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Instead of comparing two words at a time, walk down the columns of every word together. As long as every word has the same character at column i, that character belongs to the prefix. The first column where they disagree (or a word runs out) ends it.
Code
public static string LongestCommonPrefix(string[] strs) {
int len = strs.Min(w => w.Length);
int i = 0;
for (; i < len; i++) {
char c = strs[0][i];
for (int j = 1; j < strs.Length; j++)
if (strs[j][i] != c) return strs[0][..i];
}
return strs[0][..len];
}Tips
- strs.Min(w => w.Length) caps how far the scan can possibly go before any word runs out of characters.
- The moment any single word disagrees, the whole prefix is decided: no need to check the rest.
In the .NET library
Sorting the words first also works: the common prefix of the whole set equals the common prefix of just the first and last word after sorting, since those are the most different.