/14. Longest Common Prefix

14. Longest Common Prefix

Easy
Arrays47.2% acceptance

Given a list of strings, return the longest prefix that is shared by all strings in the list. If no common prefix exists, return an empty string.

Example 1

Input: [alpha, alpine, al]

Output: al

Explanation: All strings share al as the longest common prefix.

Example 2

Input: [test, testing, tester]

Output: test

Explanation: All strings share test as the longest common prefix.

Example 3

Input: [one, two, three]

Output: ''

Explanation: No common prefix among all strings.

Example 4

Input: [abc, abc, abc]

Output: abc

Explanation: All strings are identical, so the common prefix is the full string.

Constraints

  • 1 <= len(string_list) <= 200
  • 0 <= len(s) <= 200 for each s in string_list
  • Each string in string_list consists only of lowercase English letters
Python (current runtime)

Case 1

Input: ['prefix', 'prelude', 'prevent']

Expected: 'pre'

Case 2

Input: ['single']

Expected: 'single'

Case 3

Input: ['apple', 'banana', 'cherry']

Expected: ''

Case 4

Input: ['interview', 'internet', 'internal']

Expected: 'inte'

Case 5

Input: ['a', 'ab', 'abc']

Expected: 'a'