Given an array of strings, find the longest common prefix shared by all of them (e.g. ["flower","flow","flight"] -> "fl").
Take the first string as a candidate prefix and shrink it while it is not a prefix of each subsequent string; or compare column by column across all strings until a mismatch. Both are O(total characters).
public static String longestCommonPrefix(String[] arr) {
if (arr.length == 0) return "";
String prefix = arr[0];
for (int i = 1; i < arr.length; i++) {
while (!arr[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}function longestCommonPrefix(arr) {
if (arr.length === 0) return '';
let prefix = arr[0];
for (let i = 1; i < arr.length; i++) {
while (!arr[i].startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (!prefix) return '';
}
}
return prefix;
}def longest_common_prefix(arr):
if not arr:
return ''
prefix = arr[0]
for s in arr[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
if not prefix:
return ''
return prefixCommon-prefix logic drives autocomplete, routing tables, and grouping of hierarchical keys (e.g. shared path segments).
The array contains an empty string. What should the result be, and does your code handle it?