C/C++ Arena

Step 9 of 10

Two pointers from both ends

The two-pointer technique comes up constantly, in interviews and in real code. One pointer starts at the front, another at the back, and they move toward each other, doing some work at each step, until they meet.

#include <stdio.h>

int is_mirror(const int *a, int n) {
    const int *lo = a;
    const int *hi = a + n - 1;
    while (lo < hi) {
        if (*lo != *hi) {
            return 0;
        }
        lo++;
        hi--;
    }
    return 1;
}

int main(void) {
    int x[] = {1, 4, 9, 4, 1};
    int y[] = {1, 2, 3};
    printf("%d %d\n", is_mirror(x, 5), is_mirror(y, 3));
    return 0;
}
1 0

The details that matter

The example checks whether the array reads the same from both ends. Reversing uses the same walk, but instead of comparing, it swaps the two values the pointers point at. You already know how to swap through pointers from step 2.

Try it on paper with 4 and 5 elements before coding, to see exactly which pairs get touched.

Your task

Write void reverse(int *a, int n) that reverses the array in place using two pointers (no [ ]).

Challenge 2

Write int is_palindrome_arr(const int *a, int n) that returns 1 if the array reads the same forwards and backwards, using two pointers and no [ ].

Challenge 3

Write void reverse_string(char *s) that reverses a string in place with two pointers and no [ ]. You'll need to find the end of the string yourself first.

Previous: const and pointers Next: Challenge: squeeze out spaces