Remove duplicates from the sorted array in C++.

This same process, due to a sorted array, is to erase the redundant components from the array.

Examples:

Method 1: (Using extra space)

  • Generate an auxiliary temp[] array for storing different aspects.
  • Traverse the input array and duplicate different aspects from arr[] to temp[] one by one. Keep records of counting different aspects, as well. Let the count be j.
  • Copy j elements to arr[] from temp, and return j.

Example:

Output:

Remove duplicates from sorted array in CPP

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 2: (Constant extra space)

Just hold a totally separate index for the same array as kept in Method 1 for the different array.

Example:

Output:

Remove duplicates from sorted array in CPP

Time Complexity: O(n)
Auxiliary Space: O(1)

Pin It on Pinterest

Share This