forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1268-search-suggestions-system.js
46 lines (41 loc) · 1.17 KB
/
1268-search-suggestions-system.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
/**
* Binary Search
*
* Time O(n*log(n) + m*n) | Space O(m)
* https://leetcode.com/problems/search-suggestions-system/description/
* @param {string[]} products
* @param {string} searchWord
* @return {string[][]}
*/
var suggestedProducts = function(products, searchWord) {
products.sort((product1, product2) => {
if(product1 < product2) {
return -1;
}
if(product2 < product1) {
return 1;
}
if(product1 === product2) {
return 0;
}
});
const result = [];
let left = 0;
let right = products.length - 1;
for(let i = 0; i < searchWord.length; i++) {
let char = searchWord[i];
while(left <= right && (products[left].length - 1 < i || products[left][i] !== char)) {
left++;
}
while(left <= right && (products[right].length - 1 < i || products[right][i] !== char)) {
right--;
}
const subResult = [];
const len = Math.min(right - left + 1, 3);
for(let j = 0; j < len; j++) {
subResult.push(products[left+j]);
}
result.push(subResult);
}
return result;
};