File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments