Created
August 2, 2020 13:13
-
-
Save MirzaChilman/3822bc25ec0232406ce3fd214b2201b8 to your computer and use it in GitHub Desktop.
two number 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
// O(n) time | O(n) space | |
function twoNumberSub(array, targetSum){ | |
let hashNumbers = {} | |
for(const num of array){ | |
let potentialMatch = targetSum - num | |
if(potentialMatch in hashNumbers){ | |
return [potentialMatch, num] | |
}else{ | |
hashNumbers[num] = true // or whatever value you want, because we don't care about the value only key | |
} | |
} | |
return [] | |
} | |
// O(n log n) time | O(1) space | |
// if it's array try to sort it and have 2 pointes for more optimized solution | |
function twoNumberSum(array, targetSum){ | |
let leftIndices = 0 | |
let rightIndices = array.length - 1 | |
while (leftIndices < rightIndices){ | |
const currentSum = array[leftIndices] + array[rightIndices] | |
if(currentSum === targetSum) | |
return [array[leftIndices], array[rightIndices]] | |
}else if (currentSum < targetSum){ | |
leftIndices++ | |
}else if(currentSum > targetSum){ | |
rightIndices-- | |
} | |
return [] | |
} | |
twoNumberSum([-4, -1,1,3,5,6,8,1], targetSum) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment