Skip to content

Commit eb0860d

Browse files
authored
Merge pull request #922 from dsrao711/issue_921
Python solution for longest common prefix -- DSA450
2 parents 1b79528 + a491e86 commit eb0860d

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

DSA 450 GFG/LongestCommonPrefix.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Link : https://leetcode.com/problems/longest-common-prefix/submissions/
2+
3+
# Approach :
4+
5+
# Example
6+
# Input: strs = ["flower","flow","flight"]
7+
# Output: "fl"
8+
9+
# We are supposed to return the longest common prefix
10+
11+
# Variables :
12+
# prefix => longest common substring
13+
14+
# 1. Assume the longest common substring to be the first element of the list . prefix = strs[0]
15+
# 2. Iterate through the list of words and keep comparing each char of the word with the prefix
16+
# 3. If the char of word != char of prefix , reduce the prefix to last matched char
17+
# 4. If the word is shorter than the prefix , and all charachters are matched , then prefix = word
18+
19+
20+
# Working
21+
# prefix = "flower"
22+
23+
# i = 1
24+
# prefix = "flower" , word = "flow"
25+
26+
# f = f , pass
27+
# l = l , pass
28+
# o = o , pass
29+
# w = w , pass
30+
# i = 4 , 4 >= len("flow") , prefix = "flow" , break
31+
32+
33+
34+
# i = 2
35+
# prefix = "flow" , word = "flight"
36+
# f = f , pass
37+
# l = l , pass
38+
# o != i => prefix = prefix[:i] = "fl" , break
39+
40+
41+
# o/p = "fl"
42+
43+
44+
class Solution(object):
45+
def longestCommonPrefix(self, strs):
46+
"""
47+
:type strs: List[str]
48+
:rtype: str
49+
"""
50+
n = len(strs)
51+
prefix = strs[0]
52+
53+
for word in strs:
54+
for i in range(0 , len(prefix)):
55+
if(i >= len(word)):
56+
prefix = word
57+
break
58+
59+
elif(prefix[i] != word[i]):
60+
prefix = prefix[:i]
61+
break
62+
63+
return prefix
64+
65+
66+
# TC : O(mn)

0 commit comments

Comments
 (0)