Longest Common Prefix

easy string

Problem

Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

Vertical scan: pick character at column j from the first string, then check that every other string has the same character at column j. The first column where the check fails (or any string runs out of characters) is where the common prefix ends.

Input["forecast", "forensic", "forever"]
Output"fore"

def longest_common_prefix(words):
    if not words:
        return ""
    for j in range(len(words[0])):
        c = words[0][j]
        for i in range(1, len(words)):
            if j >= len(words[i]) or words[i][j] != c:
                return words[0][:j]
    return words[0]
function longestCommonPrefix(words) {
  if (words.length === 0) return "";
  for (let j = 0; j < words[0].length; j++) {
    const c = words[0][j];
    for (let i = 1; i < words.length; i++) {
      if (j >= words[i].length || words[i][j] !== c) {
        return words[0].slice(0, j);
      }
    }
  }
  return words[0];
}
class Solution {
    public String longestCommonPrefix(String[] words) {
        if (words.length == 0) return "";
        for (int j = 0; j < words[0].length(); j++) {
            char c = words[0].charAt(j);
            for (int i = 1; i < words.length; i++) {
                if (j >= words[i].length() || words[i].charAt(j) != c) {
                    return words[0].substring(0, j);
                }
            }
        }
        return words[0];
    }
}
string longestCommonPrefix(vector<string>& words) {
    if (words.empty()) return "";
    for (int j = 0; j < (int)words[0].size(); j++) {
        char c = words[0][j];
        for (int i = 1; i < (int)words.size(); i++) {
            if (j >= (int)words[i].size() || words[i][j] != c) {
                return words[0].substr(0, j);
            }
        }
    }
    return words[0];
}
Time: O(total characters) Space: O(1)