Skip to content

Featured article for the topic Two pointers · picked by the needcode team

Two pointers: shrink the search space from both ends

needcode teamFeatured AuthorPosted · 1 min read

On a sorted array, two pointers turn an O(n²) pair search into O(n).

def two_sum_sorted(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return lo, hi
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None

Each step discards one element that can't be part of any answer, so the loop runs at most n times.

Practice#

  • Container with most water
  • 3Sum
  • Remove duplicates from a sorted array
Text by needcode team, licensed under CC BY-SA 4.0. You may share and adapt it with credit to the author, under the same licence.

Other approaches to Two pointers

Submit your approach

No other approaches yet. Think you can explain it differently? Write one.

Comments

Loading comments…