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.

lock icon+19 hidden tests on Submit

challenge icon

Follow-up

Suppose the list stays fixed and you get many query words. How would you find, for each query, the longest prefix it shares with at least one word in the list, without rescanning the list each time?

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

Case 1

Case 2

Case 3

Input

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

Expected

"inter"