Two numbers that add up
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
Find the two different positions in `nums` whose values add up to `target` and return them as `[i, j]` with `i < j`. Every test has at most one such pair; return `null` when there is none. The same position cannot be used twice, but two equal values at different positions can. Do not change `nums`. One hidden test has 100,000 numbers, so comparing every pair is too slow.
What this exercise teaches
The Map turns the search for the partner into a single lookup, so the whole thing is one pass instead of a loop inside a loop. Checking the map before storing the current number is what stops a number from pairing with itself.
A hint if you get stuck
Walk the array once and keep a `Map` from each value you have seen to its index. For the current number, check whether `target - n` is already in the map before you add the number itself.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Arrays and objects
- Group by a fieldFree
- Count by a fieldFree
- Remove duplicates by a fieldFree
- Split into chunksFree
- Zip two arraysFree
- Flatten one levelFree
- Pick some keysFree
- Sort by several keysFree
- Merge settingsFree
- Omit some keysFree
- Flatten to a depthFree
- Transpose a matrixFree
- Binary searchFree
- Values in both arraysFree
- Rotate an arrayFree