Skip to content

Commit f0e2653

Browse files
committed
Finds longest common prefix string amongst an array of strings
1 parent daf5a7d commit f0e2653

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

longest_common_prefix.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Write a function to find the longest common prefix string amongst an array of strings.
2+
# If there is no common prefix, return an empty string "".
3+
4+
from typing import List
5+
from unittest import TestCase
6+
7+
8+
def longestCommonPrefix(strs: List[str]) -> str:
9+
if not strs:
10+
return ''
11+
strs.sort()
12+
min_strs, max_strs = strs[0], strs[-1]
13+
for i, letter in enumerate(min_strs):
14+
if max_strs[i] != letter:
15+
return min_strs[:i]
16+
return min_strs
17+
18+
19+
class TestsLongestCommonPrefix(TestCase):
20+
def test_empty_list(self):
21+
self.assertEqual('', longestCommonPrefix([]))
22+
23+
def test_with_one_element_in_list(self):
24+
self.assertEqual('flower', longestCommonPrefix(["flower"]))
25+
26+
def test_simple_case(self):
27+
self.assertEqual('fl', longestCommonPrefix(["flower", "flow", "flight"]))
28+
29+
def test_with_no_common_prefix(self):
30+
self.assertEqual('', longestCommonPrefix(["dog", "racecar", "car"]))
31+
32+
def test_with_common_prefix(self):
33+
self.assertEqual('a', longestCommonPrefix(["abcde", "abcdeea", "abc", "adbc"]))

0 commit comments

Comments
 (0)