Two pointers in C: solved exercise
Two pointers in C: solved exercise
If you searched for a solved two-pointer technique exercise in C, here are three classic applications: finding a pair with a target sum in a sorted array, reversing an array in-place, and removing duplicates from a sorted array — all in O(n) with no extra memory.
The two-pointer technique maintains two indices that move from opposite ends toward the center (or both from the left at different speeds) to avoid the O(n²) double loop.
Problem statement
Given the sorted array {1, 2, 3, 4, 6, 8, 11}:
- Find all pairs with sum 10.
- Reverse the array in-place.
- Given
{1, 1, 2, 2, 3, 4, 4, 5}, remove duplicates and return the new length.
C solution
Expected output
Common mistakes
- Applying two pointers on an unsorted array for pair search: the technique only works if the array is sorted.
- Not advancing both pointers when a pair is found: staying at the same index causes an infinite loop.
- Confusing the read pointer with the write pointer in duplicate removal: the write pointer advances only when a new element is found.
- Using signed indices when the array size is 0:
right = n - 1withn = 0gives -1 and the loop may not behave correctly on all compilers.
Practical use
Two pointers is a fundamental technique for array and string problems: three-sum, container with most water, palindromes, and array partitioning. It appears frequently in technical interviews and is the basis for more advanced algorithms like the sliding window.
Recommended next exercise
- Maximum subarray: Kadane in C: solved exercise
- Remove duplicates from sorted array in C
- Binary search in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why does the two-pointer technique require a sorted array?
Because the movement logic relies on comparing the sum against the target: if the sum is too small, advancing the left pointer increases it (larger elements are to the right); if too large, retreating the right pointer decreases it. Without order there is no guarantee that moving a pointer changes the sum in the right direction.
When should I use two pointers instead of a hash table?
Two pointers runs in O(n) with O(1) extra space but requires a sorted array. A hash table also gives O(n) but uses O(n) space and does not require pre-sorting. Two pointers is preferred when space is limited or the array is already sorted.
Can the technique be applied with more than two pointers?
Yes. The three-sum problem fixes one element with an outer loop and applies two pointers inside, achieving O(n²) instead of the O(n³) brute-force approach.