Skip to content

Commit 61e222e

Browse files
committed
Added two pointer solution for two sum problem
1 parent 3bbec1d commit 61e222e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Diff for: other/two_pointer.py

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

0 commit comments

Comments
 (0)