Skip to problem
←

Longest Common Prefix

Easy 0 attempts

Given a nonempty array of strings strs, return the longest string that is a prefix of every input string. A prefix starts at index 0; matching characters elsewhere do not count.

Return "" if there is no shared starting character or any input string is empty. With one input string, return that entire string.

For "flower", "flow", and "flight", the shared prefix is "fl". The next characters differ, so no longer prefix is possible.

Function contract

Implement longestCommonPrefix(strs). Receive a nonempty array of strings containing lowercase English letters; individual strings may be empty.

Output: Return the longest prefix shared by every string, or "" when none exists.

Example 1

Input
strs = ["flower","flow","flight"]
Output
"fl"

Example 2

Input
strs = ["dog","racecar","car"]
Output
""
Constraints
  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of lowercase English letters
Topics

Approach: Horizontal Scan

Take the first string as the initial prefix. Compare it against each subsequent string, comparing corresponding characters to find the matching prefix length. If the prefix ever becomes empty, short-circuit and return "".

javascript
function longestCommonPrefix(strs) {
  if (!strs.length) return '';
  let length = strs[0].length;
  for (let i = 1; i < strs.length; i++) {
    let j = 0;
    while (j < length && j < strs[i].length && strs[0][j] === strs[i][j]) j++;
    length = j;
    if (length === 0) return '';
  }
  return strs[0].slice(0, length);
}

Time Complexity: O(N + S), where N is the number of strings and S is their total character count (including the empty-string case)

Space Complexity: O(p) for the returned prefix of length p, with O(1) auxiliary space

Loading discussion…

Saved in this browser only. Private to you.

JavaScript