Last active
September 5, 2019 09:34
-
-
Save jadechip/02cda6affcacc889a8283c80eadd6b54 to your computer and use it in GitHub Desktop.
Programming challenges: Two Number Sum
This file contains 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
# Naive approach - O(n) | |
def twoNumberSum(array, targetSum): | |
for num in array: | |
if num == 0: | |
return sorted([num, targetSum]) | |
if (num < targetSum): | |
diff = targetSum - num | |
if diff in array: | |
if array.index(diff) != array.index(num): | |
result = [num, diff] | |
return sorted(result) | |
return [] | |
# Better approach - O(nlog(n)) | |
def twoNumberSum(array, targetSum): | |
array.sort() | |
left_pointer = 0 | |
right_pointer = len(array) - 1 | |
while left < right: # While the pointers don't overlap... | |
currentSum = array[left_pointer] + array[right_pointer] | |
if currentSum == targetSum: | |
return [array[left_pointer], array[right_pointer]] | |
# Increase or decrease based on size (list is already sorted) | |
elif currentSum < targetSum: | |
left_pointer += 1 | |
elif currentSum > targetSum: | |
right_pointer -= 1 | |
return [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment