Skip to content

Commit 44c85bb

Browse files
committed
Solution #14 - Nishitha - 05/08/2025 - commit #5
1 parent cbc97df commit 44c85bb

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed
Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
1-
# Problem: Longest Common Prefix
2-
## Language: C++
1+
# Leetcode Problem #14: Longest Common Prefix (Easy)
2+
3+
## Problem
4+
5+
Given an array of strings `strs`, return the **longest common prefix** string amongst them.
6+
If there is no common prefix, return an **empty string**.
37

48
---
59

6-
1. Start with the first string as the prefix.
7-
2. For each string in the array:
8-
- Reduce the prefix by comparing it with the current string.
9-
- Stop early if prefix becomes empty.
10+
## Approach
11+
12+
- Start with the first string as the **initial prefix**.
13+
- Compare it with the next string:
14+
- If the current string doesn't start with the prefix, **trim the prefix** by one character from the end.
15+
- Repeat until it matches or becomes an empty string.
16+
- Continue this for all strings in the list.
1017

1118
---
1219

1320

1421

22+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// LeetCode #14 - Longest Common Prefix
2+
// Language: C++
3+
4+
#include <string>
5+
#include <vector>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
string longestCommonPrefix(vector<string>& strs) {
12+
if (strs.empty()) return "";
13+
14+
string prefix = strs[0];
15+
16+
for (int i = 1; i < strs.size(); ++i) {
17+
int j = 0;
18+
while (j < prefix.size() && j < strs[i].size() && prefix[j] == strs[i][j])
19+
++j;
20+
prefix = prefix.substr(0, j);
21+
if (prefix.empty()) return "";
22+
}
23+
24+
return prefix;
25+
}
26+
};
27+

0 commit comments

Comments
 (0)