R@M3$H.NBlog

[ARRAY] Remove Duplicates from Sorted Array

16 October, 2013 - 7 min read

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

   1: class Solution {

   2: public:

   3:     int removeDuplicates(int A[], int n) {

   4:       if ( n <= 1 )

   5:             return n ;

   6:

   7:         int Index = 0, Itr = 1 ;

   8:

   9:         while ( Itr < n ) {

  10:             if ( A[Itr] != A[Index] )

  11:                 A[++Index] = A[Itr] ;

  12:

  13:             Itr++ ;

  14:         }

  15:

  16:         return Index + 1 ;

  17:     }

  18: };

Use two pointers, one head, one next. If A[head] == A[next], then move next forward. Otherwise, copy A[next] to A[head+1], then increment both head and next.

   1: int removeDuplicates(int A[], int n) {

   2:     // Start typing your C/C++ solution below

   3:     // DO NOT write int main() function

   4:     if (n == 0 || n == 1) {

   5:         return n;

   6:     }

   7:

   8:     int hd = 0, nx = 0;

   9:

  10:     for (; nx != n;) {

  11:         if (A[hd] == A[nx]) {

  12:             nx++;

  13:         } else {

  14:             A[++hd] = A[nx++];

  15:         }

  16:     }

  17:

  18:     return hd+1;

  19: }

What if duplicates are allowed at most twice?

For example,

Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

 

   1: class Solution {

   2: public:

   3:     int removeDuplicates(int A[], int n) {

   4:         if ( n <= 2 )

   5:             return n ;

   6:

   7:         int Index = 1 ;

   8:

   9:         for ( int Itr = 2; Itr < n; Itr++ ) {

  10:             if ( !( ( A[Index] == A[Itr] ) && ( A[Index - 1] == A[Itr] )  ) )

  11:                 A[++Index] = A[Itr] ;

  12:         }

  13:         return Index+1 ;

  14:

  15:     }

  16: };

 

Can be made generic as below:

   1: class Solution {

   2: public:

   3:     // Here k = 2

   4:     int removeDuplicates(int A[], int n, int k ) {

   5:         if ( n <= k )

   6:         return n ;

   7:

   8:         int Index = 0, Itr = 1, Count = 1 ;

   9:

  10:         while ( Itr < n ) {

  11:             if ( A[Itr] != A[Index] ) {

  12:                 A[++Index] = A[Itr] ;

  13:                 Count = 1 ;

  14:             }

  15:             else {

  16:                 if ( Count < k ){

  17:                     A[++Index] = A[Itr] ;

  18:                     Count++ ;

  19:                 }

  20:             }

  21:             Itr++ ;

  22:         }

  23:

  24:         return Index + 1 ;

  25:

  26:     }

  27: };

END