Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- QUESTION:
- Given an array of integers, and a number ‘sum’,
- return a Boolean denoting whether there is a pair
- of integers in the array whose sum is equal to ‘sum’.
- NOTE:
- Expected time complexity O(n)
- */
- const arr = [-1,1,2,5,3,4,5]
- const hasPair = (arr, sum) => {
- const comps = new Set() // set of complimenting pairs
- return arr.some(item => comps.has(item) || (comps.add(sum-item), false))
- }
- hasPair(arr, -1) // false
- hasPair(arr, 0) // true
- hasPair(arr, 8) // true
- hasPair(arr, 10) // true
- hasPair(arr, 11) // false
Add Comment
Please, Sign In to add comment