Reading history

Two Pointer Technique in C: Pair Sum, Duplicates and More

7 min read 1 views

Use the two pointer technique in C to find pairs in sorted arrays, remove duplicates in place, solve container with most water and check palindromes in O(n).

Many array and string problems look like they need two nested loops: check every pair, compare every position with every other. The two pointer technique often does the same job in one pass. You keep two indexes and move them according to a simple rule, so the work drops from O(n2) to O(n). This lesson shows the two main patterns, pointers moving towards each other and pointers moving in the same direction, with five classic problems.

In this lesson you will learn

  • The two shapes of the technique: opposite ends and slow/fast
  • How to find a pair with a given sum in a sorted array
  • How to remove duplicates in place
  • The “container with most water” problem
  • Reversing and palindrome checks with two pointers
  • Why each pointer moves at most n times

You should know arrays in C and Big O notation.

Opposite Ends: Pair With a Given Sum

In a sorted array, put one pointer at the start and one at the end. Their sum tells you which way to move.

134681115lohi1 + 15 = 16 > 14: move hi left134681115lohi1 + 11 = 12 < 14: move lo right134681115lohi3 + 11 = 14: found0123456
  • If the sum is too small, the left value is too small for every remaining partner, so move lo right.
  • If the sum is too big, the right value is too big for every remaining partner, so move hi left.
  • Each step throws away one element for good, so there are at most n − 1 steps.

Same Direction: Slow and Fast Pointers

Here both pointers go left to right. The fast pointer reads every element. The slow pointer marks where the next kept element should be written.

#include <stdio.h>

/* Pair with a given sum in a SORTED array: pointers move towards each other */
static int pair_sum(const int *a, int n, int target, int *x, int *y) {
    int lo = 0, hi = n - 1;
    while (lo < hi) {
        int s = a[lo] + a[hi];
        printf("  lo=%d hi=%d  %d + %d = %d\n", lo, hi, a[lo], a[hi], s);
        if (s == target) { *x = lo; *y = hi; return 1; }
        if (s < target) lo++;      /* need a bigger sum: move left pointer right */
        else hi--;                 /* need a smaller sum: move right pointer left */
    }
    return 0;
}

/* Remove duplicates from a sorted array in place: slow and fast pointers */
static int remove_dups(int *a, int n) {
    if (n == 0) return 0;
    int slow = 0;                  /* a[0..slow] holds the unique values */
    for (int fast = 1; fast < n; fast++)
        if (a[fast] != a[slow]) a[++slow] = a[fast];
    return slow + 1;
}

int main(void) {
    int a[] = {1, 3, 4, 6, 8, 11, 15};
    int x, y;
    printf("Find two numbers that add up to 14:\n");
    if (pair_sum(a, 7, 14, &x, &y))
        printf("Found: a[%d] + a[%d] = %d + %d\n\n", x, y, a[x], a[y]);

    int b[] = {2, 2, 3, 5, 5, 5, 8, 9, 9};
    int m = remove_dups(b, 9);
    printf("Unique values (%d):", m);
    for (int i = 0; i < m; i++) printf(" %d", b[i]);
    printf("\n");
    return 0;
}

Output

Find two numbers that add up to 14:
  lo=0 hi=6  1 + 15 = 16
  lo=0 hi=5  1 + 11 = 12
  lo=1 hi=5  3 + 11 = 14
Found: a[1] + a[5] = 3 + 11

Unique values (5): 2 3 5 8 9
  • The trace shows the pair search: 16 is too big, so hi moves; 12 is too small, so lo moves; 14 is found in three steps.
  • In remove_dups, a[0..slow] always holds the unique values seen so far. A new value is copied to a[slow + 1]. No second array is needed, so the extra space is O(1).
  • This only works because the array is sorted, so equal values sit next to each other.

More Opposite-End Problems

#include <stdio.h>

/* Container with most water: two lines and the x-axis hold water */
static int max_water(const int *h, int n) {
    int lo = 0, hi = n - 1, best = 0;
    while (lo < hi) {
        int height = h[lo] < h[hi] ? h[lo] : h[hi];
        int area = height * (hi - lo);
        if (area > best) best = area;
        if (h[lo] < h[hi]) lo++;   /* the shorter line limits the area: move it */
        else hi--;
    }
    return best;
}

/* Reverse an array in place */
static void reverse(char *s, int n) {
    for (int i = 0, j = n - 1; i < j; i++, j--) {
        char t = s[i]; s[i] = s[j]; s[j] = t;
    }
}

/* Is the string a palindrome, ignoring non-letters? */
static int is_letter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }
static char lower(char c) { return (c >= 'A' && c <= 'Z') ? (char)(c + 32) : c; }
static int palindrome(const char *s, int n) {
    int i = 0, j = n - 1;
    while (i < j) {
        if (!is_letter(s[i])) { i++; continue; }
        if (!is_letter(s[j])) { j--; continue; }
        if (lower(s[i]) != lower(s[j])) return 0;
        i++; j--;
    }
    return 1;
}

int main(void) {
    int h[] = {1, 8, 6, 2, 5, 4, 8, 3, 7};
    printf("Most water: %d\n", max_water(h, 9));

    char w[] = "algorithm";
    reverse(w, 9);
    printf("Reversed: %s\n", w);

    const char *p1 = "Never odd or even";
    const char *p2 = "Two pointers";
    printf("\"%s\" palindrome? %s\n", p1, palindrome(p1, 17) ? "yes" : "no");
    printf("\"%s\" palindrome? %s\n", p2, palindrome(p2, 12) ? "yes" : "no");
    return 0;
}

Output

Most water: 49
Reversed: mhtirogla
"Never odd or even" palindrome? yes
"Two pointers" palindrome? no
  • Container with most water: two vertical lines and the x-axis form a container. Its area is the shorter height times the distance. Moving the taller line inwards can never help, because the width shrinks and the height is still limited by the shorter line. So we always move the shorter one. The best pair here is heights 8 and 7, seven apart: 7 × 7 = 49.
  • Reverse: swap the two ends and move both pointers inwards until they meet.
  • Palindrome: compare the two ends, skipping spaces and ignoring case. One mismatch is enough to say no.

When Does It Work?

PatternTypical problemsWhat you need
Opposite endsPair sum, 3-sum, container with water, reverse, palindromeSorted data, or a rule that tells which end to discard
Slow and fastRemove duplicates, move zeros, partition, merge sorted arraysA condition for keeping an element
Fast is twice as fastMiddle of a linked list, cycle detectionA linked structure

For 3-sum (three numbers adding to a target), sort the array, fix the first number, and run the pair search on the rest. That gives O(n2) instead of O(n3).

Common Mistakes

  1. Using pair sum on an unsorted array. The moving rule is only correct when the data is sorted.
  2. Using lo <= hi for pairs, which lets an element pair with itself.
  3. Moving the taller line in the water problem, which can skip the best answer.
  4. Forgetting the empty array in remove_dups.

Practice Exercises

Exercise 1. Move all zeros in {0, 3, 0, 5, 7} to the end, keeping the other numbers in order.

Show answer

Use slow and fast pointers: copy each non-zero a[fast] to a[slow++], then fill the rest with zeros. Result: {3, 5, 7, 0, 0}.

Exercise 2. Two sorted arrays {1, 4, 9} and {2, 3, 10} must be merged. How can two pointers help?

Show answer

Keep one pointer in each array. Copy the smaller of the two current values and move that pointer. This is the merge step of merge sort, and it gives {1, 2, 3, 4, 9, 10} in O(n + m).

Frequently Asked Questions

Is two pointers the same as a sliding window?

A sliding window is a special case of same-direction pointers, where the two pointers mark the ends of a range that grows and shrinks. See the sliding window lesson for problems about subarrays.

What if the array is not sorted?

Either sort it first, which costs O(n log n), or use a hash table to find pairs in O(n) average time. Sorting is better when you need O(1) extra space.

Summary

  • Two pointers replace a nested loop with one pass, often O(n).
  • Opposite-end pointers work on sorted data: move the end that cannot be part of the answer.
  • Slow and fast pointers filter or compact an array in place.
  • Each pointer moves at most n times, which is why it is linear.

Next: Binary Search on the Answer in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *