-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlongest-common-prefix.js
55 lines (48 loc) · 1.49 KB
/
longest-common-prefix.js
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// https://leetcode.com/problems/longest-common-prefix/
// Related Topics: String, Array
// Difficulty: Easy
/*
Initial thoughts:
We are going to look at each index of every string
at the same time, comparing them to their counterpart
in the first string, adding the character to our results
if all of the strings have the same character, and returning
the results in case of a difference.
Time complexity: O(n * min(s)) where s is the length of the longest common prefix
Space complexity: O(min(s)) where s is the length of the longest common prefix
*/
/**
* @param {string[]} strs
* @return {string}
*/
const longestCommonPrefix = strs => {
if (!strs.length) return '';
const result = [];
for (let i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (strs[0][i] !== strs[j][i]) return result.join('');
}
result.push(strs[0][i]);
}
return result.join('');
};
/*
Optimization:
Using the counter variable we can forgoe the result tracking variable
and just slice and return it at the end, rendering the space complexity constant.
Time complexity: O(n * min(s)) where s is the length of the longest common prefix
Space complexity: O(1)
*/
/**
* @param {string[]} strs
* @return {string}
*/
const longestCommonPrefix = strs => {
if (!strs.length) return '';
for (var i = 0; i < strs[0].length; i++) {
for (let j = 1; j < strs.length; j++) {
if (strs[0][i] !== strs[j][i]) return strs[0].substr(0, i);
}
}
return strs[0].substr(0, i);
};