Two Pointers Checkpoint
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This checkpoint mixes all three patterns on marks, prices and chains. Decide first which pointer pattern fits the clue, then write it.
Opposite ends: use the largest at either side
Marks change from -7 to 11, sorted. Their squares are largest at the two ends. Fill a new list from the back with the larger square, moving the pointer that gave it.
def sorted_squares(nums): result = [0] * len(nums) left, right = 0, len(nums) - 1 for pos in range(len(nums) - 1, -1, -1): if abs(nums[left]) > abs(nums[right]): result[pos] = nums[left] ** 2 left += 1 else: result[pos] = nums[right] ** 2 right -= 1 return result
print(sorted_squares([-7, -3, 2, 3, 11]))Example 1 · Pairs under a budget
prices = sorted([40, 10, 25, 5, 30])budget = 50left, right = 0, len(prices) - 1count = 0while left < right: if prices[left] + prices[right] < budget: count += right - left left += 1 else: right -= 1print(count)6
What this code does
- Sorted prices are 5, 10, 25, 30, 40. With a budget of 50, 5 + 40 fits, so 5 pairs with all four others at once.
- Counting right - left pairs at once keeps it O(n) after the sort.
Each value is used once, so it is O(n) time. Sorting the squares would cost O(n log n).
Same direction: keep what passes a test
Read visits every score and write collects the kept ones at the front. The order of kept scores never changes, and no second list is needed.
def remove_value(nums, bad): write = 0 for read in range(len(nums)): if nums[read] != bad: nums[write] = nums[read] write += 1 return write
scores = [4, 9, 4, 7, 4]kept = remove_value(scores, 4)print(kept, scores[:kept])Example 2 · Negative marks to the end
marks = [5, -1, 8, -1, 3]write = 0for read in range(len(marks)): if marks[read] != -1: marks[write], marks[read] = marks[read], marks[write] write += 1print(marks)[5, 8, 3, -1, -1]
What this code does
- Valid marks are swapped to the front, so -1 values gather at the back.
- The order of 5, 8, 3 is kept.
The answer is the first kept cells. Cells after that hold old values.
Choose the pattern from the clue
Sorted data and a pair or triple points to pointers from both ends. Filtering or compacting in place points to read and write. A chain or a repeating sequence points to fast and slow.
Example 3 · Happy numbers with a hand-made loop
def step(n): return sum(int(d) ** 2 for d in str(n))
def is_happy(n): slow, fast = n, step(n) while fast != 1 and slow != fast: slow = step(slow) fast = step(step(fast)) return fast == 1
print(is_happy(7), is_happy(4))True False
What this code does
- 7 reaches 1 in a few steps, so it is happy.
- 4 falls into a loop, so fast meets slow without reaching 1.
Example 4 · Choose the pattern from the clue
def count_triples(nums): nums = sorted(nums) count = 0 for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total < 0: left += 1 elif total > 0: right -= 1 else: count += 1 left += 1 right -= 1 while left < right and nums[left] == nums[left - 1]: left += 1 return count
print(count_triples([-1, 0, 1, 2, -1, -4]))2
What this code does
- Three sum is the opposite-end pattern inside a loop, so it costs O(n squared).
- Skipping equal values keeps each triple unique.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Print whether any two values of the sorted list [1, 4, 6, 8, 10, 45] add up to 16.
True
Exercise 2· Easy
Reverse the list [1, 2, 3, 4, 5] in place with two pointers and print it.
[5, 4, 3, 2, 1]
Exercise 3· Easy
Remove every 0 from [0, 5, 0, 0, 7, 9] in place. Print the kept values.
[5, 7, 9]
Exercise 4· Medium
Print the squares of [-6, -2, 1, 4, 5] in sorted order, using two pointers and no sort call.
[1, 4, 16, 25, 36]
Exercise 5· Medium
Print the number of unique values in the sorted list [1, 1, 2, 3, 3, 3, 4] using a write pointer.
4
Exercise 6· Medium
Print the unique triples of [-3, -1, 0, 1, 2, 3] that add up to zero.
[[-3, 0, 3], [-3, 1, 2], [-1, 0, 1]]
Exercise 7· Medium
Print the middle value of the chain values = [3, 6, 9, 12, 15, 18, 21] with next links [1, 2, 3, 4, 5, 6, -1], using fast and slow pointers.
12
Exercise 8· Hard
Print the repeated number in [2, 5, 9, 6, 9, 3, 8, 9, 7, 1] using fast and slow pointers.
9
Interview questions
Questions interviewers ask on this topic.
Finish up
Mark complete & continue
Next: Must-do problems: Two Pointers