File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Solution-1: Brute Force Approach
2
+ // Time: O(N^2)
3
+ // Space: O(N)
4
+
5
+ class Solution {
6
+ public:
7
+ string longestCommonPrefix (vector<string>& strs) {
8
+ int n=strs.size ();
9
+ string res = " " ;
10
+ sort (strs.begin (), strs.end ());
11
+ string longString = strs[n-1 ];
12
+ for (int t=0 ; t<longString.size ();t++){
13
+ char temp = longString[t];
14
+ for (int i=0 ;i<strs.size ();i++){
15
+ if (strs[i][t] != temp){
16
+ return res;
17
+ }
18
+ }
19
+ res+=temp;
20
+ }
21
+ return res;
22
+ }
23
+ };
24
+
25
+ // Solution-2: Optimal Approach
26
+ // Time: O(N*logN)
27
+ // Space: O(N)
28
+
29
+ class Solution {
30
+ public:
31
+ string longestCommonPrefix (vector<string>& strs) {
32
+ int n=strs.size ();
33
+ string res = " " ;
34
+ sort (strs.begin (), strs.end ());
35
+ string smallString = strs[0 ], largeString = strs[n-1 ];
36
+ for (int i=0 ; i<smallString.size ();i++){
37
+ if (smallString[i] != largeString[i]){
38
+ return res;
39
+ }
40
+ res+=smallString[i];
41
+ }
42
+ return res;
43
+ }
44
+ };
You can’t perform that action at this time.
0 commit comments