v9.1.1
Menu

Longest Common Prefix

easyFREEArrays & StringsMicrosoft DSA

Given an array of strings, find the longest common prefix among all strings. If none, return "".

Example

Input
flower,flow,flight
Output
fl
Reasoning
  • Input: a list of words, here flower, flow and flight (lengths 6, 4 and 6). A prefix is the first kk letters of a word; the answer is the largest kk for which all three words begin with the same kk letters.
  • Upper bound: a shared prefix can never be longer than the shortest word, so here k≤4k \le 4 (the length of flow).
  • Position 1: the words start with f, f, f. All agree, so k≥1k \ge 1.
  • Position 2: l, l, l. Still unanimous, so k≥2k \ge 2.
  • Position 3: o, o, i. flight disagrees, so no prefix of length 3 is shared by everyone, and nothing longer can be either. Hence k=2k = 2 and the output is fl.
  • Notice: one disagreeing word is enough to cap the answer. For the words dog, racecar and car the very first letters differ, so k=0k = 0 and the result is the empty string; a list holding only abc returns abc itself.

Constraints

  • 1 <= len(strs) <= 200
  • 0 <= len(strs[i]) <= 200
  • strs[i] consists of lowercase English letters

More from Microsoft DSA

solution.py

Test results

Sign in to run your code against the test cases.