KatInterview

Shared Starting Sequence in String Array

StringsAuto-graded · 22 test cases
EasyAuto-gradedStringsstringsarraysprefix

Last updated

Determine the longest initial substring shared across every word in a given list.

Given a collection of strings strs, determine the longest prefix that is shared by every string in the list.

If the input collection has no shared prefix among all strings, or if the list is empty, return an empty string "".

Constraints

  • 0 <= len(strs) <= 200
  • 0 <= len(strs[i]) <= 200
  • strs[i] consists only of lowercase English letters ('a' through 'z').

Examples

Example 1

Input: longest_common_prefix(['flower', 'flow', 'flight'])

Output: 'fl'

Example 2

Input: longest_common_prefix(['dog', 'racecar', 'car'])

Output: ''

Hints

Hint 1

Start by assuming the first string is the common prefix candidate.

Hint 2

Compare the candidate character-by-character against each remaining string, trimming it whenever a mismatch occurs.

Hint 3

If your candidate prefix becomes empty at any point, you can immediately return an empty string.