Skip to content

Commit 1ec340c

Browse files
Improve two_pointer documentation and readability
Enhanced the docstring for better clarity, added explanation of approach, time and space complexity, and improved formatting.
1 parent fc2f947 commit 1ec340c

1 file changed

Lines changed: 22 additions & 11 deletions

File tree

maths/two_pointer.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,32 @@
1-
"""
1+
"""
2+
Two Pointer Technique for Two Sum Problem (Sorted Array)
3+
24
Given a sorted array of integers, return indices of the two numbers such
35
that they add up to a specific target using the two pointers technique.
46
5-
You may assume that each input would have exactly one solution, and you
6-
may not use the same element twice.
7+
Assumptions:
8+
- The input array is sorted in non-decreasing order.
9+
- Each input has exactly one solution.
10+
- The same element cannot be used twice.
711
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]
12+
Approach:
13+
- Initialize two pointers:
14+
left pointer at the beginning (index 0)
15+
right pointer at the end (index n-1)
16+
- Compare sum of elements at both pointers:
17+
- If sum == target → return indices
18+
- If sum < target → move left pointer forward
19+
- If sum > target → move right pointer backward
1120
12-
Example:
13-
Given nums = [2, 7, 11, 15], target = 9,
21+
Time Complexity: O(n)
22+
Space Complexity: O(1)
1423
15-
Because nums[0] + nums[1] = 2 + 7 = 9,
16-
return [0, 1].
24+
Example:
25+
Input: nums = [2, 7, 11, 15], target = 9
26+
Output: [0, 1]
1727
18-
[1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
28+
Reference:
29+
https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
1930
"""
2031

2132
from __future__ import annotations

0 commit comments

Comments
 (0)