Created
October 26, 2021 12:14
-
-
Save cagataycali/c58ced67516f49f45f2a62a7b5fd65c8 to your computer and use it in GitHub Desktop.
[JavaScript] Two sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = require('assert'); | |
| function twoNumberSum(array, targetSum) { | |
| // Hold the difference, | |
| const memo = {}; | |
| let result = []; | |
| // Use .some higher order function for break the loop when found. | |
| // You can prefer basic for loop with `break` | |
| array.some(num => { | |
| // We will find the pair in this object. | |
| /** | |
| * memo = { [10 - 11]: 11 } // -1 is the right pair for hitting the target. | |
| */ | |
| // When the `-1` came to te que, we already now, -1 and 11 is pair for target. | |
| if (memo[num] !== undefined) { | |
| // I found the pairs, | |
| result = [num, memo[num]]; | |
| // Break the loop. | |
| return true; | |
| } | |
| /* | |
| memo = { | |
| [10 - 3]: 3 // 7: 3, In here, 7 is the right pair for hitting the target. | |
| } | |
| */ | |
| memo[targetSum - num] = num; | |
| }) | |
| return result; | |
| } | |
| assert.deepStrictEqual(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10), [-1, 11]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment