Skip to content

Commit 3b289b2

Browse files
committed
added Longest Common Prefix
1 parent 64d3d2d commit 3b289b2

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

Easy/LongestCommonPrefix/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Longest Common Prefix
2+
[Leetcode Link](https://leetcode.com/problems/longest-common-prefix/)
3+
4+
## Problem:
5+
6+
Write a function to find the longest common prefix string amongst an array of strings.
7+
8+
If there is no common prefix, return an empty string "".
9+
10+
## Example:
11+
12+
```
13+
Input: ["flower","flow","flight"]
14+
Output: "fl"
15+
```
16+
```
17+
Input: ["dog","racecar","car"]
18+
Output: ""
19+
Explanation: There is no common prefix among the input strings.
20+
```
21+
22+
## Note:
23+
24+
All given inputs are in lowercase letters `a-z`.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
def longestCommonPrefix(strs):
3+
"""
4+
Write a function to find the longest common prefix string amongst an array of strings.
5+
If there is no common prefix, return an empty string "".
6+
"""
7+
common = ""
8+
if len(strs) == 0:
9+
return common
10+
for i in range(len(strs[0])):
11+
prefix = strs[0][i]
12+
for j in range(1, len(strs)):
13+
if i >= len(strs[j]) or strs[j][i] != prefix:
14+
return common
15+
common += prefix
16+
return common
17+
18+
input = ["flower", "flow", "flight"]
19+
output = longestCommonPrefix(input)
20+
print("Input:", input)
21+
print("Output:", output)
22+
23+
input = ["dog", "racecar", "car"]
24+
output = longestCommonPrefix(input)
25+
print("Input:", input)
26+
print("Output:", output)

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Languages used: Java and Python
1111
- Easy
1212
- [Sum of Even Numbers After Queries](Easy/SumOfEvenNumbersAfterQueries)
1313
- [Next Greater Element 1](Easy/NextGreaterElement1)
14+
- [Longest Common Prefix](Easy/LongestCommonPrefix)
1415
- Medium
1516
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
1617
- [Distribute Coins in Binary Tree](#Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)