Two Pointer Technique on Arrays in DSA C - Time & Space Complexity
We want to understand how fast the two pointer technique works on arrays.
Specifically, how the number of steps changes as the array gets bigger.
Analyze the time complexity of the following code snippet.
int left = 0, right = n - 1;
while (left < right) {
if (arr[left] + arr[right] == target) {
// found pair
break;
} else if (arr[left] + arr[right] < target) {
left++;
} else {
right--;
}
}
This code uses two pointers moving from both ends of a sorted array to find a pair that sums to a target.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The while loop moving pointers left and right.
- How many times: Each pointer moves at most n times combined, so up to n steps.
As the array size grows, the total steps grow 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 increase directly with input size, not faster or slower.
Time Complexity: O(n)
This means the time to find the pair grows in a straight line with the array size.
[X] Wrong: "Since there are two pointers, the time is O(n²)."
[OK] Correct: The pointers move towards each other and each element is visited at most once, so total steps are linear, not squared.
Understanding this technique shows you can solve problems efficiently by smartly scanning arrays.
"What if the array was not sorted? How would the time complexity change?"
Practice
Two Pointer Technique when used on arrays?Solution
Step 1: Understand the technique
The two pointer technique involves using two indices or pointers to scan the array, often from the start and end, to solve problems efficiently.Step 2: Identify the correct description
Use two indices to traverse the array from different ends or positions simultaneously. correctly describes using two pointers to traverse the array from different ends or positions simultaneously.Final Answer:
Use two indices to traverse the array from different ends or positions simultaneously. -> Option CQuick Check:
Two pointers move from different positions = A [OK]
- Thinking two pointers mean two separate arrays
- Confusing pointers with storing sums
- Assuming pointers swap elements randomly
left and right for an array arr of size n in C?Solution
Step 1: Understand pointer initialization
For two pointers starting at the beginning and end of an array,leftshould be 0 andrightshould ben - 1because array indices start at 0.Step 2: Check options
int left = 0, right = n - 1; correctly initializesleft = 0andright = n - 1. Other options have incorrect indices.Final Answer:
int left = 0, right = n - 1; -> Option AQuick Check:
Start at 0 and end at n-1 = C [OK]
- Starting left at 1 instead of 0
- Setting right to n (out of bounds)
- Swapping left and right initialization
int arr[] = {1, 3, 5, 7, 9};
int left = 0, right = 4;
int sum = 0;
while (left < right) {
sum += arr[left] + arr[right];
left++;
right--;
}
printf("%d", sum);Solution
Step 1: Trace the loop iterations
Initial pointers: left=0, right=4
Iteration 1: sum=0+(1+9)=10, left=1, right=3
Iteration 2: sum=10+(3+7)=20, left=2, right=2
Loop ends because left is not less than right.Step 2: Calculate final sum
Sum after loop = 20. Note that the middle element (index 2) is not added because left == right stops the loop.Final Answer:
20 -> Option DQuick Check:
Sum pairs (1+9)+(3+7) = 20 [OK]
- Including middle element when left == right
- Adding elements twice
- Incorrect loop condition
int arr[] = {2, 4, 6, 8, 10};
int left = 0, right = 4;
int target = 14;
while (left <= right) {
int sum = arr[left] + arr[right];
if (sum == target) {
printf("Found");
break;
} else if (sum < target) {
left++;
} else {
right--;
}
}Solution
Step 1: Analyze loop condition
The loop usesleft <= right, which allows pointers to meet or cross. This can cause incorrect checks or double counting.Step 2: Correct loop condition
Usingleft < rightensures pointers do not cross and only valid pairs are checked.Final Answer:
The loop condition should be left < right, not left <= right. -> Option BQuick Check:
Pointers must not cross: left < right [OK]
- Using <= instead of < in loop condition
- Swapping pointer increment/decrement logic
- Incorrect pointer initialization
arr of size n, how can you use the two pointer technique to find all unique pairs that sum to a target value t? Choose the best approach.Solution
Step 1: Use two pointers at array ends
Start withleft = 0andright = n - 1. Calculate sum of elements at these pointers.Step 2: Move pointers and skip duplicates
If sum equals target, record pair and move both pointers skipping duplicates. If sum < target, move left pointer right. If sum > target, move right pointer left.Final Answer:
Initialize two pointers at start and end; move pointers inward based on sum comparison; skip duplicates to find unique pairs. -> Option AQuick Check:
Two pointers from ends + skip duplicates = D [OK]
- Using nested loops instead of two pointers
- Not skipping duplicates causing repeated pairs
- Moving both pointers forward instead of inward
Ready to prove it?
Pass the test and this pattern moves unknown
