Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.37 KB | None | 0 0
  1. function pairs(array, target) {
  2. // Cache to hold visited elements as keys and index as value O(n) space
  3. const cache = {};
  4.  
  5. // O(n) iteration of array
  6. return array.reduce((output, val, i) => {
  7. let diff = target - val;
  8.  
  9. if (cache.hasOwnProperty(diff)) {
  10. output.push([cache[diff], i]);
  11. }
  12.  
  13. cache[val] = i;
  14.  
  15. return output;
  16. }, []);
  17. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement