Two Pointer Technique on Arrays in DSA Rust - Time & Space Complexity
We want to understand how fast the two pointer technique works when scanning arrays.
How does the number of steps change as the array gets bigger?
Analyze the time complexity of the following code snippet.
fn two_pointer_sum(arr: &[i32], target: i32) -> bool {
let (mut left, mut right) = (0, arr.len() - 1);
while left < right {
let sum = arr[left] + arr[right];
if sum == target {
return true;
} else if sum < target {
left += 1;
} else {
right -= 1;
}
}
false
}
This code checks if two numbers in a sorted array add up to a target using two pointers moving inward.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop moves two pointers through the array.
- How many times: Each pointer moves at most the length of the array once.
As the array size grows, the total steps increase roughly in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps grow directly with input size, not faster or slower.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the array gets bigger.
[X] Wrong: "Since there are two pointers, the time is O(n²) because of nested loops."
[OK] Correct: The pointers move inward without repeating the same positions, so total steps add up to n, not n times n.
Knowing how two pointers scan arrays efficiently helps you solve many problems quickly and confidently.
"What if the array was not sorted? How would the time complexity change if we still tried this two pointer approach?"
Practice
Two Pointer Technique when used on arrays?Solution
Step 1: Understand the technique
The two pointer technique uses two indices or pointers to traverse the array, often from opposite ends or different positions.Step 2: Identify the purpose
This helps solve problems like finding pairs, removing duplicates, or partitioning efficiently without extra space.Final Answer:
Use two indices to scan the array from different ends or positions simultaneously -> Option DQuick Check:
Two pointers = two indices scanning array [OK]
- Confusing two pointers with two separate arrays
- Assuming sorting is always required
- Thinking recursion is part of two pointer technique
arr?Solution
Step 1: Check pointer initialization
Two pointers usually start at the beginning (0) and end (length - 1) of the array.Step 2: Verify mutability and valid indices
Pointers must be mutable to move, and indices must be within array bounds (0 to len-1).Final Answer:
let (mut left, mut right) = (0, arr.len() - 1); -> Option BQuick Check:
Start pointers at 0 and len-1 with mut [OK]
- Using non-mutable pointers when they need to move
- Setting pointers outside array bounds
- Swapping start and end indices
let arr = vec![1, 2, 3, 4, 5];
let (mut left, mut right) = (0, arr.len() - 1);
let mut sum_pairs = Vec::new();
while left < right {
sum_pairs.push(arr[left] + arr[right]);
left += 1;
right -= 1;
}
println!("{:?}", sum_pairs);Solution
Step 1: Trace pointer movements and sums
Initially, left=0, right=4: sum = 1+5=6; then left=1, right=3: sum = 2+4=6; loop stops when left=2, right=2.Step 2: Collect sums in vector
The sums collected are [6, 6].Final Answer:
[6, 6] -> Option AQuick Check:
Pairs sums = [6, 6] [OK]
- Not stopping loop when pointers meet
- Adding wrong pairs or indices
- Off-by-one errors in pointer updates
let arr = vec![1, 2, 3, 7, 8];
let (mut left, mut right) = (0, arr.len());
while left < right {
let sum = arr[left] + arr[right];
if sum == 10 {
println!("Found");
break;
} else if sum < 10 {
left += 1;
} else {
right -= 1;
}
}Solution
Step 1: Check pointer initialization
right is set to arr.len(), which is one past the last valid index (arr.len() - 1).Step 2: Understand consequences
Accessing arr[right] causes an out-of-bounds error and program panic.Final Answer:
right is initialized to arr.len(), which is out of bounds -> Option CQuick Check:
Array indices go 0 to len-1 [OK]
- Using arr.len() as index instead of arr.len() - 1
- Incorrect loop condition allowing invalid access
- Mixing addition and subtraction in sum calculation
Solution
Step 1: Use two pointers from start and end
Initialize left at 0 and right at last index, move inward based on sum comparison.Step 2: Skip duplicates after finding a valid pair
After adding a pair, increment left while next value equals current, decrement right similarly to avoid duplicates.Final Answer:
Move left and right pointers inward, skipping duplicates after finding a valid pair -> Option AQuick Check:
Skip duplicates by moving pointers after valid pair [OK]
- Not skipping duplicates causing repeated pairs
- Using nested loops instead of two pointers
- Moving only one pointer regardless of sum
Ready to prove it?
Pass the test and this pattern moves unknown
