AlgoMaster Logo

Longest Common Prefix

easyFrequency6 min readUpdated June 23, 2026

Understanding the Problem

A prefix of a string is any leading substring. For example, the prefixes of "flower" are "", "f", "fl", "flo", "flow", "flowe", and "flower". The longest common prefix (LCP) is the longest string that is a prefix of every string in the array.

Two properties bound the answer. Any string in the array can be empty, and an empty string shares no characters, so if even one string is "", the answer is "". And the LCP can never be longer than the shortest string in the array, since a prefix of a shorter string cannot exceed that string's length.

The challenge is comparing characters across all strings efficiently.

Key Constraints:

  • 1 <= strs.length <= 200 → The array has at most 200 strings, so the total character count is small. Time complexity is not the binding concern here; any reasonable scan passes.
  • 0 <= strs[i].length <= 200 → A string can be empty, which forces an empty answer. Every approach must handle this case.
  • Only lowercase English letters → No unicode or special characters to handle.

Approach 1: Vertical Scanning

Intuition

Check the common prefix one character position at a time. Look at position 0 of every string. If they all match, move to position 1, and continue until a position where the characters differ or some string runs out of characters.

With the strings stacked as rows in a grid, this scans down each column. The prefix ends at the first column that is not uniform, or when the shortest string ends.

Algorithm

  1. If the array is empty, return ""
  2. For each character position i starting from 0:
    • Get the character at position i from the first string
    • For every other string in the array:
      • If i equals the length of that string (we've run past it), return the prefix so far
      • If the character at position i doesn't match, return the prefix so far
  3. If we get through all characters of the first string without stopping, the entire first string is the common prefix

Example Walkthrough

1Check column 0: flower[0]='f', flow[0]='f', flight[0]='f' → All match
0
i=0
f
1
l
2
o
3
w
4
e
5
r
1/4

Code

Vertical scanning is already optimal in the worst case, since every character of the prefix has to be confirmed against every string at least once. The next approach uses a property of lexicographic order to avoid touching most strings at all.

Approach 2: Sorting

Intuition

If you sort the array of strings lexicographically, the first and last strings in sorted order are the two that differ earliest. Any prefix common to both of these extremes must also be common to every string between them.

This holds because sorting orders strings by their characters from left to right. If the first sorted string starts with "fl" and the last sorted string also starts with "fl", then every string between them starts with "fl" too, otherwise it would have sorted before the first or after the last. So instead of comparing all n strings, sort once and compare two.

Algorithm

  1. If the array is empty, return ""
  2. Sort the array of strings lexicographically
  3. Compare the first and last strings character by character
  4. The common prefix of these two strings is the answer

Example Walkthrough

1Input: ["flower", "flow", "flight"]. After sorting: ["flight", "flow", "flower"]
0
first
flight
1
flow
2
last
flower
1/5

Code

Sorting reduces the work to two strings but pays the O(n m log n) sort cost. The next approach splits the array into halves and combines partial results, which is useful when the strings are spread across machines or computed in parallel.

Approach 3: Divide and Conquer

Intuition

The LCP of an array equals the LCP of two values: the LCP of the left half and the LCP of the right half. Formally, LCP(S1, ..., Sn) = LCP(LCP(S1, ..., Smid), LCP(Smid+1, ..., Sn)). This is associative because a prefix shared by every string in both halves is a prefix shared by every string overall.

Split the array until each piece is a single string (which is its own LCP), then combine results back up by finding the common prefix of two strings at each level. The structure mirrors merge sort: split, solve each half, combine.

Algorithm

  1. If the array is empty, return ""
  2. Call a recursive function findLCP(strs, left, right):
    • Base case: If left == right, return strs[left] (a single string is its own prefix)
    • Divide: Find mid = (left + right) / 2
    • Conquer: Recursively find lcpLeft = findLCP(strs, left, mid) and lcpRight = findLCP(strs, mid + 1, right)
    • Combine: Return the common prefix of lcpLeft and lcpRight

Example Walkthrough

1Split ["flower","flow","flight","fly"] into left=["flower","flow"] and right=["flight","fly"]
0
flower
1
flow
2
flight
3
fly
1/4

Code