Menu
CoddyTech

Longest Common Prefix

You get an array of words strs. Return the longest string that every word starts with. If the words do not all begin with the same letter, return the empty string "". A word counts as a prefix of itself, so a single word is its own answer.

Function

longestCommonPrefix(strs: string-array) → string
strsstring-array
the words to compare
Returnsstring
the longest prefix all the words share, or an empty string

Constraints

  • 1 ≤ strs.length ≤ 200
  • 1 ≤ strs[i].length ≤ 200
  • Every word contains only lowercase English letters.

Examples

Input
strs = ["interview", "internet", "interval", "internal"]
Output
"inter"
Explanation
All four words begin with inter. At the next position interview and interval have a v, internet and internal an n, so the prefix stops there.
challenge icon

Follow-up

Suppose the list stays fixed and many query words arrive. How would you find each query's longest prefix shared with some word in the list, without rescanning the list?

Reset code
def longestCommonPrefix(strs):
    # Write code here

Test #1

Test #2

Test #3

Argument

strs = ["interview", "internet", "interval", "internal"]

Expected Output

"inter"