File tree 2 files changed +54
-0
lines changed
2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // the best case [O(n)] using SET data structure
2
+ function findTwoNumsAddingToN ( arr , number ) {
3
+ const pair = [ ] ;
4
+ const store = new Set ( ) ;
5
+
6
+ for ( let i = 0 ; i < arr . length ; i += 1 ) {
7
+ // check if the set contains one of the element that sum upto the given number
8
+ if ( store . has ( number - arr [ i ] ) ) {
9
+ pair . push ( number - arr [ i ] ) ;
10
+ pair . push ( arr [ i ] ) ;
11
+ break ;
12
+ }
13
+ // push the element in the set
14
+ store . add ( arr [ i ] ) ;
15
+ }
16
+ return pair . length ? pair : false ;
17
+ }
18
+
19
+ // the Brute force approach
20
+ function findTwoNumsAddingToN2 ( arr , number ) {
21
+ const pair = [ ] ;
22
+ for ( let i = 0 ; i < arr . length ; i += 1 ) {
23
+ for ( let j = i + 1 ; j < arr . length ; j += 1 ) {
24
+ if ( arr [ i ] + arr [ j ] === number ) {
25
+ pair . push ( arr [ i ] , arr [ j ] ) ;
26
+ break ;
27
+ }
28
+ }
29
+ }
30
+
31
+ return pair . length ? pair : false ;
32
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * You may find it easy but it's tricky for few
3
+ * Input - [9, 2, 3, 6]
4
+ * Output - 6
5
+ */
6
+
7
+ function findSecondMax ( arr ) {
8
+ let max = arr [ 0 ] ;
9
+ let max2 = Number . MIN_SAFE_INTEGER ;
10
+
11
+ for ( let el of arr ) {
12
+ if ( el > max ) {
13
+ max2 = max ;
14
+ max = el ;
15
+ }
16
+
17
+ if ( el < max && el > max2 ) {
18
+ max2 = el ;
19
+ }
20
+ }
21
+ return max2 ;
22
+ }
You can’t perform that action at this time.
0 commit comments