Bird
0
0
DSA Cprogramming~3 mins

Why Remove Duplicates from Sorted Array Two Pointer in DSA C?

Choose your learning style9 modes available
The Big Idea

Discover how two simple pointers can save you hours of tedious duplicate removal!

The Scenario

Imagine you have a long list of sorted numbers, but some numbers repeat many times. You want to keep only one copy of each number. Doing this by checking each number again and again by hand is tiring and slow.

The Problem

Manually scanning the list and removing duplicates means you have to compare each number with all others, which takes a lot of time and can easily cause mistakes like missing duplicates or deleting the wrong number.

The Solution

The two-pointer method uses two markers to scan the list just once. One pointer moves forward to find new unique numbers, and the other keeps track of where to place them. This way, duplicates are removed quickly and safely.

Before vs After
Before
for (int i = 0; i < n; i++) {
  for (int j = i + 1; j < n; j++) {
    if (arr[i] == arr[j]) {
      // remove duplicate manually
    }
  }
}
After
int uniqueIndex = 0;
for (int currentIndex = 1; currentIndex < n; currentIndex++) {
  if (arr[currentIndex] != arr[uniqueIndex]) {
    uniqueIndex++;
    arr[uniqueIndex] = arr[currentIndex];
  }
}
What It Enables

This method lets you quickly clean up sorted lists by removing duplicates in just one pass, saving time and effort.

Real Life Example

When you have a sorted list of customer IDs and want to send a message to each unique customer only once, this method helps you find all unique IDs fast.

Key Takeaways

Manual duplicate removal is slow and error-prone.

Two-pointer method scans once and removes duplicates efficiently.

It works best on sorted arrays where duplicates are together.