Lesson 4/25 ยท ๐ Linear Structures
๐ Linear StructuresLesson 4/25
Phase 1 ยท Linear Structures18 min
Two Pointers Technique
Turn O(nยฒ) brute force into elegant O(n) solutions
The two pointers technique uses two variables that traverse a data structure, often from opposite ends, to solve problems that would otherwise need nested loops.
It's one of the most powerful patterns in coding interviews. Master it and you'll solve dozens of problems.
It's one of the most powerful patterns in coding interviews. Master it and you'll solve dozens of problems.
Two Sum on a sorted array, O(n)python
def two_sum_sorted(nums, target):
"""Find two numbers that sum to target. nums is sorted."""
left, right = 0, len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1 # Need bigger sum โ move left pointer right
else:
right -= 1 # Need smaller sum โ move right pointer left
return []
print(two_sum_sorted([1, 2, 3, 4, 6], 6)) # โ [1, 3]"racecar", compare rโr, aโa, cโc, all match โ palindrome
๐In the Real World...
Merging two sorted arrays in merge sort uses two pointers, one for each array, advancing the pointer for whichever element is smaller. This is what makes merge sort O(n log n) instead of O(nยฒ).
๐คQuick Check
When is the two-pointer technique applicable?
Practice Exercises
0/2 solvedExercise 1 of 2medium
โฑ 00:00Palindrome Check
Use two pointers to check if a string is a palindrome (ignoring non-alphanumeric characters and case).
Expected output:
Expected output:
TrueFalsesolution.py
1 / 2
Exercise 2 of 2medium
โฑ 00:00Container With Most Water
Given heights of walls, find two walls that form a container with maximum water area.Area = min(height[left], height[right]) ร (right - left)
Expected output:
Expected output:
49solution.py
2 / 2
Solve all 2 exercises to unlock completion