Code Logo

Longest Common Prefix

Published at05 Jan 2026
Substring Easy 11 views
Like23

Given an array of strings, find the longest common prefix string shared among all of them. If there is no common prefix, return an empty string.

For example, the longest common prefix of ["flower", "flow", "flight"] is "fl". The prefix of ["dog", "racecar", "car"] is "" (no common prefix). A single string ["hello"] has prefix "hello". An empty array returns "".

Finding the longest common prefix is a classic string problem used in autocomplete, IP routing (longest prefix matching), and DNA sequence alignment. It tests character-by-character comparison across multiple strings.

The solution takes the first string as a reference. For each character position, check if all other strings have the same character at that position. If any string is shorter or has a different character, return the prefix found so far.

Edge cases include an empty array (return ""), a single string (return that string), strings with no common characters (return ""), and all strings being identical (return any of them).

Example Input & Output

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

Longest common prefix is "fl".

Algorithm Flow

Recommendation Algorithm Flow for Longest Common Prefix
Recommendation Algorithm Flow for Longest Common Prefix

Solution Approach

Compare characters at each position across all strings until a mismatch is found.

function longestCommonPrefix(strs)
  if strs is empty then return ""
  prefix = ""
  for i = 0 to length(strs[0]) - 1
    c = strs[0][i]
    for j = 1 to length(strs) - 1
      if i >= length(strs[j]) or strs[j][i] != c then return prefix
    prefix = prefix + c
  return prefix

Handle the empty array case. Take the first string as reference. For each character position, get the character from the first string and check it against the same position in every other string. If any string is too short or has a different character, return the prefix built so far. Otherwise, append the character to the prefix.

Time complexity is O(n * m) where n is the number of strings and m is the shortest string length. Space complexity is O(1) for the prefix.

Best Answers

java
import java.util.*;

class Solution {
    public String artisan_label_string(String[] labels) {
        if (labels.length == 0) return "";
        String[] sortedArr = labels.clone();
        Arrays.sort(sortedArr);
        return String.join("\n", sortedArr);
    }
}