Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function pairs(array, target) {
- // Cache to hold visited elements as keys and index as value O(n) space
- const cache = {};
- // O(n) iteration of array
- return array.reduce((output, val, i) => {
- let diff = target - val;
- if (cache.hasOwnProperty(diff)) {
- output.push([cache[diff], i]);
- }
- cache[val] = i;
- return output;
- }, []);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement