|
1 | | -""" |
| 1 | + """ |
| 2 | +Two Pointer Technique for Two Sum Problem (Sorted Array) |
| 3 | +
|
2 | 4 | Given a sorted array of integers, return indices of the two numbers such |
3 | 5 | that they add up to a specific target using the two pointers technique. |
4 | 6 |
|
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. |
7 | 11 |
|
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 |
11 | 20 |
|
12 | | -Example: |
13 | | -Given nums = [2, 7, 11, 15], target = 9, |
| 21 | +Time Complexity: O(n) |
| 22 | +Space Complexity: O(1) |
14 | 23 |
|
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] |
17 | 27 |
|
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 |
19 | 30 | """ |
20 | 31 |
|
21 | 32 | from __future__ import annotations |
|
0 commit comments