Longest common prefix

Scan column by column across every word at once. The prefix ends the moment one word disagrees.

Time O(n·m)Space O(1)Code C#
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

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.