File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
src/_Problems_/find-2-nums-adding-to-n Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ // the best case using a data structure - SET
2+ function findTwoNumsAddingToN ( arr , sum ) {
3+ const nums = [ ] ;
4+ const store = new Set ( ) ;
5+
6+ for ( let i = 0 ; i < arr . length ; i ++ ) {
7+ // check if the set contains one of the pir that sum upto given sum
8+ if ( store . has ( sum - arr [ i ] ) ) {
9+ nums . push ( sum - arr [ i ] ) ;
10+ nums . push ( arr [ i ] ) ;
11+ break ;
12+ }
13+ // push the element in the set
14+ store . add ( arr [ i ] ) ;
15+ }
16+ return nums . length ? nums : false ;
17+ }
18+
19+ // the Brute force approach
20+ function findTwoNumsAddingToN2 ( arr , sum ) {
21+ const nums = [ ] ;
22+ for ( let i = 0 ; i < arr . length ; i ++ ) {
23+ for ( let j = i + 1 ; j < arr . length ; j ++ ) {
24+ if ( arr [ i ] + arr [ j ] === sum ) {
25+ nums . push ( arr [ i ] , arr [ j ] ) ;
26+ break ;
27+ }
28+ }
29+ }
30+
31+ return nums . length ? nums : false ;
32+ }
You can’t perform that action at this time.
0 commit comments