MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / two_pointer

Function two_pointer

maths/two_pointer.py:24–54  ·  view source on GitHub ↗

>>> 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) [] >

(nums: list[int], target: int)

Source from the content-addressed store, hash-verified

22
23
24def two_pointer(nums: list[int], target: int) -> list[int]:
25 """
26 >>> two_pointer([2, 7, 11, 15], 9)
27 [0, 1]
28 >>> two_pointer([2, 7, 11, 15], 17)
29 [0, 3]
30 >>> two_pointer([2, 7, 11, 15], 18)
31 [1, 2]
32 >>> two_pointer([2, 7, 11, 15], 26)
33 [2, 3]
34 >>> two_pointer([1, 3, 3], 6)
35 [1, 2]
36 >>> two_pointer([2, 7, 11, 15], 8)
37 []
38 >>> two_pointer([3 * i for i in range(10)], 19)
39 []
40 >>> two_pointer([1, 2, 3], 6)
41 []
42 """
43 i = 0
44 j = len(nums) - 1
45
46 while i < j:
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
57if __name__ == "__main__":

Callers 1

two_pointer.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected