Loading
0x30Lesson 4 of 13

Walk inward with two pointers

Use two indices to solve sorted-array and palindrome problems in O(n).

20 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Recognize when two pointers apply.
  • Move pointers based on a comparison.
  • Solve pair-sum problems on sorted input without extra space.

The two pointers pattern keeps two indices into a sequence and moves them toward each other (or in the same direction) based on what they see. It usually turns an O(n²) pair search into O(n) with O(1) extra space. The key requirement is structure you can exploit - most often, sorted input.

How the pointers move

  • Opposite ends: start at left = 0 and right = n - 1. For a pair sum on sorted input: if the sum is too small, move left right to increase it; if too large, move right left.
  • Palindromes: compare characters at both ends and move inward.
  • Same direction (fast/slow): one pointer reads, the other writes - used to remove duplicates in place or partition an array.
solution.py
1def is_palindrome(text):
2    chars = [c.lower() for c in text if c.isalnum()]
3    left, right = 0, len(chars) - 1
4    while left < right:
5        if chars[left] != chars[right]:
6            return False
7        left += 1
8        right -= 1
9    return True
10
11print(is_palindrome("A man, a plan, a canal: Panama"))
12print(is_palindrome("race a car"))
Output
True
False

Why is moving a pointer safe? In a sorted pair search, if nums[left] + nums[right] is too small, then nums[left] paired with anything at or before right is also too small, so left can never be part of the answer - discard it. Being able to say this out loud is what convinces an interviewer your solution is correct.

Key takeaways

  • Two pointers turn many O(n²) pair searches into O(n).

  • Sorted input is the usual signal.

  • Be ready to justify why each pointer move is safe.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: solve interview problems

Solve a classic interview problem in Python and run it against test cases. Aim for the optimal complexity, then check the edge cases. Exercises run locally in your browser.

Exercise 1

Find a pair in a sorted array

+25 XP

Read a line of integers sorted in ascending order and then a target. Using two pointers, print the 0-based indices of a pair that sums to the target (smaller index first), or none if there is no such pair.

  • Pair exists
  • No pair
main.py
Loading editor…

Python runs in a sandboxed browser worker with a 60 second time limit. Its runtime loads from the Pyodide CDN; your code stays in this browser.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…