← Back to libraryQuestion 65 of 273
⌨️Java CodingIntermediate

Longest Common Prefix

📌 Definition:

Given an array of strings, find the longest common prefix shared by all of them (e.g. ["flower","flow","flight"] -> "fl").

📖 Detailed Explanation:

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).

💻 Solutions:
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 prefix
🔑 Key Points:
  • Shrink a candidate prefix, or compare column-by-column
  • Empty array / empty string -> empty prefix
  • Stop at the shortest string length
  • O(n * m) over n strings of length m
🌍 Real-World Example:

Common-prefix logic drives autocomplete, routing tables, and grouping of hierarchical keys (e.g. shared path segments).

🎯 Scenario-Based Interview Question:

The array contains an empty string. What should the result be, and does your code handle it?