Explorer
Data Structures & Algorithms

Find the longest common prefix among an array of strings.

Problem Statement

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 `""`.

Examples

Input: strs = ["flower", "flow", "flight"]

Output: "fl"

Explanation: "fl" is the longest prefix shared by all strings.

Input: strs = ["dog", "racecar", "car"]

Output: ""

Explanation: No common prefix exists among all input strings.

Complexity

Time Complexity: O(S)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Initialize prefix as the entire first string. šŸ’” Hint 2: For each subsequent string, shrink prefix from the right until it is a prefix of strs[i]. šŸ’” Hint 3: If prefix becomes empty, return "" immediately.

Editorial & Approach

Problem Overview & Intuition

Start with strs[0] as the candidate prefix. As we iterate through subsequent strings, shorten the prefix from the end until strs[i].startsWith(prefix). If prefix becomes empty, there is no common prefix.

Step-by-Step Approach

  1. If strs.length === 0, return "".
  2. Initialize prefix = strs[0].
  3. Loop through strings from index 1.
  4. While strs[i].indexOf(prefix) !== 0: shorten prefix = prefix.slice(0, -1).
  5. If prefix === "", return "".
  6. Return prefix.

Optimal Implementation (JavaScript)

function longestCommonPrefix(strs) {
  if (!strs.length) return "";
  let prefix = strs[0];
  for (let i = 1; i < strs.length; i++) {
    while (strs[i].indexOf(prefix) !== 0) {
      prefix = prefix.slice(0, -1);
      if (!prefix) return "";
    }
  }
  return prefix;
}

Complexity Analysis

Time Complexity O(S) where S is the sum of characters across all strings.
Space Complexity O(1) auxiliary space.

Edge Cases & Corner Traps Handled

  • No common prefix: returns "".
  • All strings identical.
  • Array of single string: returns that string.

Longest Common Prefix

Easy
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 `""`.
Example Scenarios
1Example 1
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Explanation:

"fl" is the longest prefix shared by all strings.

2Example 2
Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation:

No common prefix exists among all input strings.

Editor
Loading Editor...
strs =
["flower", "flow", "flight"]
Output:Click "Run" above to execute and verify your code here.
fl