Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 22 additions & 11 deletions maths/two_pointer.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
"""
"""

Check failure on line 1 in maths/two_pointer.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (invalid-syntax)

maths/two_pointer.py:1:1: invalid-syntax: Unexpected indentation

Check failure on line 1 in maths/two_pointer.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (invalid-syntax)

maths/two_pointer.py:1:1: invalid-syntax: Unexpected indentation
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.

You may assume that each input would have exactly one solution, and you
may not use the same element twice.
Assumptions:
- The input array is sorted in non-decreasing order.
- Each input has exactly one solution.
- The same element cannot be used twice.

This is an alternative solution of the two-sum problem, which uses a
map to solve the problem. Hence can not solve the issue if there is a
constraint not use the same index twice. [1]
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

Example:
Given nums = [2, 7, 11, 15], target = 9,
Time Complexity: O(n)
Space Complexity: O(1)

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]

[1]: https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
Reference:
https://github.com/TheAlgorithms/Python/blob/master/other/two_sum.py
"""

from __future__ import annotations

Check failure on line 32 in maths/two_pointer.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (invalid-syntax)

maths/two_pointer.py:32:1: invalid-syntax: Expected a statement

Check failure on line 32 in maths/two_pointer.py

View workflow job for this annotation

GitHub Actions / ruff

ruff (invalid-syntax)

maths/two_pointer.py:32:1: invalid-syntax: Expected a statement


def two_pointer(nums: list[int], target: int) -> list[int]:
Expand Down
Loading