Skip to content

Commit 3b5f062

Browse files
committed
Add Sorted Two Sum
1 parent 5249551 commit 3b5f062

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Python/Two_Sum_Sorted.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#Question: Given a sorted list of numbers, find two numbers that add to a given target
2+
#Solution: Keep left and right pointers and adjust accordingly
3+
#Difficulty: Easy
4+
5+
def twoSum(numbers, target):
6+
"""
7+
:type numbers: List[int]
8+
:type target: int
9+
:rtype: List[int]
10+
"""
11+
#left and right pointers
12+
l, r = 0, len(numbers) - 1
13+
#while left is less than right
14+
while l < r:
15+
#If left + right is the target return them
16+
if numbers[l] + numbers[r] == target: return [l, r]
17+
#If its more then the target we need to find smaller numbers to add so move right pointer down
18+
elif numbers[l] + numbers[r] > target: r -= 1
19+
#If its more move left pointer up
20+
else: l += 1
21+
return []

0 commit comments

Comments
 (0)