python
37 lines · 9 steps
Two-pointer search on sorted arrays
How the two-pointer technique solves two-sum and three-sum on sorted input without nested brute force.
Explained by
highlit
1def two_sum_sorted(numbers, target):
2 """Find indices of two values that sum to target in a sorted array."""
3 left, right = 0, len(numbers) - 1
4 while left < right:
5 current = numbers[left] + numbers[right]
6 if current == target:
7 return (left, right)
8 elif current < target:
9 left += 1
10 else:
11 right -= 1
12 return None
13
14
15def three_sum_zero(numbers):
16 """Find all unique triplets in a sorted array that sum to zero."""
17 result = []
18 n = len(numbers)
19 for i in range(n - 2):
20 if i > 0 and numbers[i] == numbers[i - 1]:
21 continue
22 left, right = i + 1, n - 1
23 while left < right:
24 total = numbers[i] + numbers[left] + numbers[right]
25 if total == 0:
26 result.append((numbers[i], numbers[left], numbers[right]))
27 left += 1
28 right -= 1
29 while left < right and numbers[left] == numbers[left - 1]:
30 left += 1
31 while left < right and numbers[right] == numbers[right + 1]:
32 right -= 1
33 elif total < 0:
34 left += 1
35 else:
36 right -= 1
37 return result
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1On a sorted array, two pointers converging from both ends find a target pair in linear time instead of quadratic.
- 2Three-sum reduces to fixing one element and running two-sum on the remainder.
- 3Skipping equal neighbors after a match is what keeps the triplet results unique.
Related explainers
python
import argparse import sys from pathlib import Path
Building a subcommand CLI with argparse
cli
argparse
subcommands
Intermediate
6 steps
python
from collections.abc import Mapping from typing import Any, Iterator
Flattening nested config into dotted keys
recursion
generators
tree-traversal
Intermediate
7 steps
java
public class SortedListMerger { public static int[] merge(int[] a, int[] b) { int[] result = new int[a.length + b.length];
Merging two sorted arrays in Java
two-pointers
merging
arrays
Beginner
6 steps
python
import csv import io from datetime import datetime
Streaming a CSV export in Flask
streaming
generators
csv
Intermediate
9 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
Intermediate
7 steps
python
from django.conf import settings from django.contrib.auth import get_user_model from django.core.mail import EmailMultiAlternatives from django.db.models.signals import post_save
Sending a welcome email with Django signals
signals
email
user-activation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/two-pointer-search-on-sorted-arrays-explained-python-569d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.