Mid From PDF Coding C# Coding Interview

Find the longest common prefix among a list of strings?

public string LongestCommonPrefix(string[] strs) {
if (strs == null || strs.Length == 0) return "";
for (int i = 0; i < strs[0].Length; i++) {
char c = strs[0][i];
for (int j = 1; j < strs.Length; j++) {
if (i == strs[j].Length || strs[j][i] != c)
return strs[0].Substring(0, i);
}
}
return strs[0];
}

Follow on:

Explanation:

Check character by character across all strings until mismatch.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details