If you're learning algorithms or preparing for coding interviews, you've probably come across the term two pointers. It sounds fancy, but it's actually one of the easiest and most useful tricks for solving array and string problems efficiently.
In this post, I'll explain what two pointers are, how they work, and walk through a few simple examples.
π What Are Two Pointers?
The idea is simple: use two variables (pointers) to iterate through an array or string.
There are two main styles:
- Start one pointer at the beginning, the other at the end β and move them toward each other.
- Move both pointers in the same direction, often at different speeds (like chasing/sliding windows).
π€ Example 1: Valid Palindrome:
Input1: "racecar"
Explanation:
Left to right: "racecar"
Right to left: "racecar"
β
They match β it's a palindrome
Output: True
Input2:βhelloβ
Explanation:
Left to right: "hello"
Right to left: "olleh"
β Not a match
Output: False
β Brute Force (not effective)
for i from 0 to length(s) - 1:
reversed = ""
for j from length(s) - 1 down to 0:
reversed = reversed + s[j]
if s != reversed:
return false
return true
- Time Complexity:
O(n^2)
, Space:O(n)
β Two Pointers (effective)
left = 0
right = length(s) - 1
while left < right:
if s[left] != s[right]:
return false
left = left + 1
right = right - 1
return true
- Without extra space
- Time complexity:
O(n)
, space:O(1)
Here, two pointers move from each end toward the middle and compare characters.
β± Time complexity: O(n)
π€ Example 2: Remove Duplicates from Sorted Array
We want to remove duplicates in-place and return the new length of the array with only unique elements at the start.
Input1: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: [0, 1, 2, 3, 4]
β Brute Force (not effective)
new_array = []
for i from 0 to length(arr) - 1:
if arr[i] not in new_array:
append arr[i] to new_array
return new_array
- Creates a new array
- Does not modify in-place
- Uses
O(n)
extra space - Time Complexity:
O(n^2)
(due toin
check in array each time)
β Two Pointers (effective)
left = 0
right = 1
while right < len(nums):
if nums[right] != nums[left]:
left += 1
nums[left] = nums[right]
right += 1
return left + 1
-
read
scans through the array -
write
marks the next position for a unique value - Overwrites the input array in-place
- Time Complexity:
O(n)
, Space:O(1)
β When Should You Use It?
Use two pointers when:
- The array is sorted
- You need to find pairs, subarrays, or ranges
- You want an efficient
O(n)
solution instead of brute-forceO(nΒ²)
π― Practice Problems
Try these to get started:
βοΈ Final Thoughts
Two pointers is a beginner-friendly technique that you'll see in many interviews.
It helps you write simple and fast code.
If this post was helpful β let me know!
Top comments (0)