-
-
Notifications
You must be signed in to change notification settings - Fork 50.4k
Expand file tree
/
Copy pathtwo_pointer.py
More file actions
72 lines (58 loc) · 1.68 KB
/
two_pointer.py
File metadata and controls
72 lines (58 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
Two Pointer Technique for Two Sum Problem (Sorted Array)
Given a sorted array of integers, return indices of the two numbers such
that they add up to a specific target using the two pointers technique.
Assumptions:
- The input array is sorted in non-decreasing order.
- Each input has exactly one solution.
- The same element cannot be used twice.
Approach:
- Initialize two pointers:
left pointer at the beginning (index 0)
right pointer at the end (index n-1)
- Compare sum of elements at both pointers:
- If sum == target → return indices
- If sum < target → move left pointer forward
- If sum > target → move right pointer backward
Time Complexity: O(n)
Space Complexity: O(1)
Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Reference:
https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
"""
from __future__ import annotations
def two_pointer(nums: list[int], target: int) -> list[int]:
"""
>>> two_pointer([2, 7, 11, 15], 9)
[0, 1]
>>> two_pointer([2, 7, 11, 15], 17)
[0, 3]
>>> two_pointer([2, 7, 11, 15], 18)
[1, 2]
>>> two_pointer([2, 7, 11, 15], 26)
[2, 3]
>>> two_pointer([1, 3, 3], 6)
[1, 2]
>>> two_pointer([2, 7, 11, 15], 8)
[]
>>> two_pointer([3 * i for i in range(10)], 19)
[]
>>> two_pointer([1, 2, 3], 6)
[]
"""
i = 0
j = len(nums) - 1
while i < j:
if nums[i] + nums[j] == target:
return [i, j]
elif nums[i] + nums[j] < target:
i = i + 1
else:
j = j - 1
return []
if __name__ == "__main__":
import doctest
doctest.testmod()
print(f"{two_pointer([2, 7, 11, 15], 9) = }")