One idea
Two pointers and sliding windows avoid checking every pair or every subarray again and again.
Move only the pointer that can still improve the answer. This is why these patterns are usually linear after sorting, or linear on the original array.
When to use
Use two pointers when the problem has a sorted array, a pair condition, or two ends of a sequence. Common examples: pair sum in a sorted array, remove duplicates, reverse vowels, container with most water.
Use sliding window when the answer is a contiguous part. Common examples: maximum sum of k elements, longest substring without repeating characters, smallest subarray with sum at least target.
Pick the pattern
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Common mistake
Do not sort blindly. Sorting changes original positions. If the question asks for original indices, store value-index pairs or use another method.
Also do not move both pointers every time. Usually one pointer moves because of a condition. For pair sum in a sorted array: if sum is small, move left rightwards. If sum is large, move right leftwards.
Example solution
Problem: Given a sorted array and a target, return whether any two numbers add to target.
This is a good repo problem because the brute force is easy to explain, and the pointer improvement is clear.
def has_pair_sum(nums, target):
left = 0
right = len(nums) - 1
while left < right:
current = nums[left] + nums[right]
if current == target:
return True
if current < target:
left += 1
else:
right -= 1
return False
print(has_pair_sum([1, 2, 4, 6, 9], 10)) # True: 1 + 9 or 4 + 6
print(has_pair_sum([1, 2, 4, 6, 9], 20)) # FalseWindow example
Problem: Maximum sum of any k consecutive elements. This is a fixed-size sliding window.
First build the first window. Then slide by adding the new item and removing the item that left.
def max_sum_k(nums, k):
if k <= 0 or k > len(nums):
return None
window_sum = sum(nums[:k])
best = window_sum
for right in range(k, len(nums)):
window_sum += nums[right]
window_sum -= nums[right - k]
best = max(best, window_sum)
return best
print(max_sum_k([2, 1, 5, 1, 3, 2], 3)) # 9, from [5, 1, 3]Write the explanation
In your README, write why each pointer moves. This is what an interviewer checks when you talk through the solution.
Use AI to draft the explanation if you want. Then check that it states the invariant, the movement rule, and the time complexity correctly.
Problem: Pair sum in sorted array
Pattern: Two pointers
Idea: Keep left at the smallest value and right at the largest value.
Move left when the sum is too small. Move right when the sum is too large.
Why it works: The array is sorted, so these moves are the only ones that can fix the sum.
Time: O(n)
Space: O(1)Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done