Skip to content

Commit 0693247

Browse files
shabab477stokhos
authored andcommitted
Added two pointer solution for two sum problem (TheAlgorithms#3468)
1 parent 9a12e55 commit 0693247

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Diff for: other/two_pointer.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Given a sorted array of integers, return indices of the two numbers such
3+
that they add up to a specific target using the two pointers technique.
4+
5+
You may assume that each input would have exactly one solution, and you
6+
may not use the same element twice.
7+
8+
This is an alternative solution of the two-sum problem, which uses a
9+
map to solve the problem. Hence can not solve the issue if there is a
10+
constraint not use the same index twice. [1]
11+
12+
Example:
13+
Given nums = [2, 7, 11, 15], target = 9,
14+
15+
Because nums[0] + nums[1] = 2 + 7 = 9,
16+
return [0, 1].
17+
18+
[1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
19+
"""
20+
from __future__ import annotations
21+
22+
23+
def two_pointer(nums: list[int], target: int) -> list[int]:
24+
"""
25+
>>> two_pointer([2, 7, 11, 15], 9)
26+
[0, 1]
27+
>>> two_pointer([2, 7, 11, 15], 17)
28+
[0, 3]
29+
>>> two_pointer([2, 7, 11, 15], 18)
30+
[1, 2]
31+
>>> two_pointer([2, 7, 11, 15], 26)
32+
[2, 3]
33+
>>> two_pointer([1, 3, 3], 6)
34+
[1, 2]
35+
>>> two_pointer([2, 7, 11, 15], 8)
36+
[]
37+
>>> two_pointer([3 * i for i in range(10)], 19)
38+
[]
39+
>>> two_pointer([1, 2, 3], 6)
40+
[]
41+
"""
42+
i = 0
43+
j = len(nums) - 1
44+
45+
while i < j:
46+
47+
if nums[i] + nums[j] == target:
48+
return [i, j]
49+
elif nums[i] + nums[j] < target:
50+
i = i + 1
51+
else:
52+
j = j - 1
53+
54+
return []
55+
56+
57+
if __name__ == "__main__":
58+
import doctest
59+
60+
doctest.testmod()
61+
print(f"{two_pointer([2, 7, 11, 15], 9) = }")

0 commit comments

Comments
 (0)