File tree Expand file tree Collapse file tree 3 files changed +54
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 3 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ var threeSum = function ( nums ) {
2
+ nums . sort ( ( a , b ) => a - b ) ;
3
+ const results = [ ] ;
4
+ for ( let i = 0 ; i < nums . length - 2 ; i ++ ) {
5
+ if ( i > 0 && nums [ i ] === nums [ i - 1 ] ) continue ;
6
+ let left = i + 1 ;
7
+ let right = nums . length - 1 ;
8
+ while ( left < right ) {
9
+ const currSum = nums [ i ] + nums [ left ] + nums [ right ] ;
10
+
11
+ if ( currSum == 0 ) {
12
+ results . push ( [ nums [ i ] , nums [ left ] , nums [ right ] ] ) ;
13
+ left ++ ;
14
+ right -- ;
15
+ // to avoid duplicates
16
+ while ( left < right && nums [ left ] === nums [ left - 1 ] ) left ++ ;
17
+ while ( left < right && nums [ right ] === nums [ right + 1 ] ) right -- ;
18
+ } else if ( currSum < 0 ) {
19
+ left ++ ;
20
+ } else right -- ;
21
+ }
22
+ }
23
+ return results ;
24
+ } ;
25
+
26
+ // Time complexity: O(n^2);
27
+ // Space complexity: O(n)
Original file line number Diff line number Diff line change
1
+ var maxProfit = function ( prices ) {
2
+ // set the initial value to Infinity so that it can always return minimum value
3
+ let minPrice = Infinity ;
4
+ let maxPrice = 0 ;
5
+ for ( i = 0 ; i < prices . length ; i ++ ) {
6
+ minPrice = Math . min ( prices [ i ] , minPrice ) ;
7
+ maxPrice = Math . max ( maxPrice , prices [ i + 1 ] - minPrice ) ;
8
+ }
9
+ return maxPrice ;
10
+ } ;
11
+
12
+ // Time complexity: O(n) - Iterating through the array
13
+ // Space complexity: O(1)
Original file line number Diff line number Diff line change
1
+ var groupAnagrams = function ( strs ) {
2
+ const map = new Map ( ) ;
3
+
4
+ for ( const str of strs ) {
5
+ // split the string into each character (returns an array) => sort it => convert it to string
6
+ const sortedStr = str . split ( '' ) . sort ( ) . join ( '' ) ;
7
+ // use the sorted Str as unique keys in the map
8
+ if ( map . has ( sortedStr ) ) {
9
+ map . get ( sortedStr ) . push ( str ) ;
10
+ } else map . set ( sortedStr , [ str ] ) ;
11
+ }
12
+ // convert values into an array
13
+ return [ ...map . values ( ) ] ;
14
+ } ;
You can’t perform that action at this time.
0 commit comments