Skip to content

Commit d6b3417

Browse files
authored
Create 1268-search-suggestions-system.js
Solved search-suggestions-system in JS.
1 parent 794f343 commit d6b3417

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Diff for: javascript/1268-search-suggestions-system.js

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Binary Search
3+
*
4+
* Time O(n*log(n) + m*n) | Space O(m)
5+
* https://leetcode.com/problems/search-suggestions-system/description/
6+
* @param {string[]} products
7+
* @param {string} searchWord
8+
* @return {string[][]}
9+
*/
10+
var suggestedProducts = function(products, searchWord) {
11+
12+
products.sort((product1, product2) => {
13+
if(product1 < product2) {
14+
return -1;
15+
}
16+
if(product2 < product1) {
17+
return 1;
18+
}
19+
if(product1 === product2) {
20+
return 0;
21+
}
22+
});
23+
24+
const result = [];
25+
let left = 0;
26+
let right = products.length - 1;
27+
for(let i = 0; i < searchWord.length; i++) {
28+
let char = searchWord[i];
29+
30+
while(left <= right && (products[left].length - 1 < i || products[left][i] !== char)) {
31+
left++;
32+
}
33+
while(left <= right && (products[right].length - 1 < i || products[right][i] !== char)) {
34+
right--;
35+
}
36+
37+
const subResult = [];
38+
const len = Math.min(right - left + 1, 3);
39+
for(let j = 0; j < len; j++) {
40+
subResult.push(products[left+j]);
41+
}
42+
result.push(subResult);
43+
}
44+
45+
return result;
46+
};

0 commit comments

Comments
 (0)