Bird
0
0
DSA Cprogramming~3 mins

Why Two Pointer Technique on Arrays in DSA C?

Choose your learning style9 modes available
The Big Idea

What if you could find pairs in a list without checking every single combination?

The Scenario

Imagine you have a long list of numbers and you want to find pairs that add up to a certain value. Doing this by checking every possible pair one by one feels like searching for a needle in a haystack.

The Problem

Checking every pair means a lot of repeated work and takes a long time, especially if the list is very long. It's easy to make mistakes or miss pairs because you have to remember which pairs you already checked.

The Solution

The two pointer technique uses two markers moving through the list from different ends. This way, you can find pairs quickly without checking every combination, saving time and effort.

Before vs After
Before
for (int i = 0; i < n; i++) {
    for (int j = i + 1; j < n; j++) {
        if (arr[i] + arr[j] == target) {
            // found pair
        }
    }
}
After
int left = 0, right = n - 1;
while (left < right) {
    int sum = arr[left] + arr[right];
    if (sum == target) {
        // found pair
        left++;
        right--;
    } else if (sum < target) {
        left++;
    } else {
        right--;
    }
}
What It Enables

This technique makes it easy and fast to solve problems involving pairs or sections of arrays without wasting time on unnecessary checks.

Real Life Example

Think of two people starting at opposite ends of a line trying to find two friends whose combined ages match a number. Instead of asking everyone, they move closer or farther based on the total age, quickly finding the right pair.

Key Takeaways

Manual pair checking is slow and error-prone.

Two pointers move from both ends to find pairs efficiently.

This method reduces time and simplifies searching in sorted arrays.