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 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"] Output: "" Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i] consists of only lowercase English letters.Problem Overview: Given an array of strings, return the longest prefix shared by every string. If no common prefix exists, return an empty string. The challenge is comparing characters efficiently without repeatedly scanning the same portions of each string.
Approach 1: Horizontal Scanning (O(S) time, O(1) space)
This approach iteratively compares prefixes across the array. Start with the first string as the candidate prefix. Then compare it with the second string and shrink the prefix until both match. Continue scanning across the remaining strings, trimming the prefix whenever a mismatch appears. Each comparison uses simple character checks such as str.startswith(prefix) or manual iteration. Because every character across all strings is examined at most once, the total work is proportional to the total number of characters S across the array. The algorithm uses constant extra space since it only maintains the current prefix.
Horizontal scanning works well for typical interview inputs because it is straightforward and avoids unnecessary data structures. You repeatedly reduce the candidate prefix until all strings share it. If the prefix becomes empty at any step, you can terminate early.
Approach 2: Divide and Conquer (O(S) time, O(log n) space)
This approach splits the array into two halves and recursively computes the longest common prefix for each half. Once you obtain two prefixes, compare them character by character to find their shared prefix. The final answer emerges by merging results up the recursion tree.
The key insight is that the longest prefix of the entire array must also be the prefix shared by the left and right halves. Instead of comparing every string against one global prefix repeatedly, the algorithm solves smaller subproblems and merges results. The total number of character comparisons across all merges is still bounded by S, the total length of all strings. Recursive splitting introduces O(log n) call stack space.
This method demonstrates strong algorithmic thinking and mirrors patterns used in merge sort or segment tree construction. While slightly more complex than scanning, it becomes useful when practicing recursive problem decomposition.
Many developers also discuss a Trie-based approach where characters are inserted into a prefix tree and traversal stops when branching occurs. Although conceptually clean, building the trie adds overhead and extra memory, making it less practical than direct string comparison. Since the problem primarily involves prefix comparison across a list of strings, most implementations rely on efficient operations from the string domain.
Recommended for interviews: Horizontal scanning is the expected solution in most coding interviews. It is simple, runs in O(S) time with O(1) space, and demonstrates clean reasoning about prefix reduction. Discussing divide and conquer afterward shows deeper algorithmic understanding and familiarity with recursive problem splitting.
In this approach, you start with the first string as a reference and gradually compare it with each subsequent string in the array. The reference prefix is shortened until it matches the prefixes of all strings.
This implementation starts by taking the first string as the initial prefix. It iteratively checks if this prefix is valid for each string, adjusting it until all strings have a common start. If a mismatch occurs, we shorten the prefix from the end.
C++
Java
Python
C#
JavaScript
Time Complexity: O(S), where S is the sum of all characters in all strings.
Space Complexity: O(1), as we are using constant extra space.
This approach involves dividing the array of strings into two halves, recursively finding the longest common prefix for each half, and merging the results. The merge step compares characters from the two strings to find the common prefix.
This C solution reduces the problem into finding the longest common prefix of smaller sections, leading to a combination of results using a helper function to merge prefixes by character comparison.
C++
Java
Python
C#
JavaScript
Time Complexity: O(S), where S is the sum of all characters in the strings.
Space Complexity: O(M*logN), where M is the length of the common prefix and N is the number of strings.
| Approach | Complexity |
|---|---|
| Horizontal Scanning | Time Complexity: O(S), where S is the sum of all characters in all strings. |
| Divide and Conquer | Time Complexity: O(S), where S is the sum of all characters in the strings. |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Horizontal Scanning | O(S) | O(1) | Best general solution for interviews and typical inputs |
| Divide and Conquer | O(S) | O(log n) | When practicing recursive problem decomposition or discussing algorithm design |
Longest Common Prefix - Leetcode 14 - Python • NeetCode • 217,791 views views
Watch 9 more video solutions →Practice Longest Common Prefix with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor