Data Structures & Algorithms Two Pointers
💡
Exercise 35

Two Pointer Technique 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

The Two Pointer technique uses two pointers to scan through data efficiently. It often turns O(n²) brute force into O(n)! 👆👆

💡 Think of it like this: Imagine two runners on a track. They can start from opposite ends and walk toward each other, or one can walk ahead while the other follows. By coordinating their movements, they can solve problems much faster than if one person checked every spot.

Three common patterns:

  • 🔀 Opposite ends: One pointer at start, one at end, move inward (palindrome check, 2Sum on sorted array)
  • 🏃‍♂️ Same direction (fast/slow): Both start at beginning, fast moves ahead (remove duplicates, linked list cycle)
  • ↔️ Two arrays: One pointer in each array (merge sorted arrays)
# Pattern 1: Opposite ends — Is it a palindrome? def isPalindrome(s): left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True # Pattern 2: Fast & Slow — Remove duplicates in sorted array def removeDuplicates(nums): slow = 0 for fast in range(1, len(nums)): if nums[fast] != nums[slow]: slow += 1 nums[slow] = nums[fast] return slow + 1

When to use two pointers: Sorted arrays, palindrome checks, partitioning, finding pairs that sum to a target. The key insight is that sorted data lets us make smart decisions about which pointer to move!

📋 Instructions
Use two pointers to find if a sorted array has two numbers that sum to a target. Given `nums = [1, 2, 3, 4, 6]` and `target = 6`, print `True` (because 2 + 4 = 6). Given `nums = [1, 2, 3, 4, 6]` and `target = 12`, print `False`.
Start left at 0, right at end. If sum < target, move left up. If sum > target, move right down. If equal, found it!
🧪 Test Cases
Input
has_pair_sum([1, 2, 3, 4, 6], 6)
Expected
True
Boolean check
Input
has_pair_sum([1, 2, 3, 4, 6], 12)
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.