AlgoInsight

DSA problem

Longest Common Prefix

EasyStringsPattern: String Traversaltop300AmazonGoogle

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

The longest common prefix is the longest string that is a prefix of every string in the input array. For example, the longest common prefix of ["flower", "flow", "flight"] is "fl", since "fl" begins every word but "flo" does not. The comparison is case-sensitive and must use entire matching characters from the start of each word.

Examples

Example 1
Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: All three words start with "fl"; the next character differs ("flo" vs "fli"), so the longest common prefix is "fl".
Example 2
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings, so the function returns an empty string.
Example 3
Input: strs = ["interspecies","interstellar","interstate"]
Output: "inters"
Explanation: Every word begins with "inters" but the seventh characters differ.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringtriestring-traversal

Browse all DSA problems