- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem_014.py
More file actions
Latest commit
30 lines (26 loc) · 1.07 KB
/
Copy pathproblem_014.py
File metadata and controls
30 lines (26 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
"""
Problem: https://leetcode.com/problems/longest-common-prefix/
Solution: Initially, we consider the first string as common prefix.
We then iteratively check if th common prefix is matching with each string.
If it is not matching we return an empty string.
If it matches partially we make the partially matched string as the new common prefix.
Time Complexity: O(n*m) where n is the total number of string and m is max length of string.
Space Complexity: O(m) as we're creating a common prefix string.
"""
classSolution:
deflongestCommonPrefix(self, strs: List[str]) ->str:
common_prefix=strs[0]
common_prefix_len=len(strs[0])
forsinstrs:
curr_len=0
foriinrange(min(common_prefix_len, len(s))):
cur_len=0
ifcommon_prefix[i] ==s[i]:
curr_len+=1
elifcurr_len==0:
return""
else:
break
common_prefix=s[:curr_len]
common_prefix_len=curr_len
returncommon_prefix