(Remove Duplicates from Sorted Array)

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].

Thoughts:
This question is actually simpler than what it looks. We just need one scan with two pointers. The first pointer points to the last index of subarray with distinct elements (hence it starts with 0). The second pointer goes through the array, starting from index 1.If the numbers referred by two pointers are different, we pad the number from back to head.

Code (Java):

public class Solution {
    public int removeDuplicates(int[] A) {
        int j = 0;
        if(A.length == 0)
            return 0;
        for(int i = 1; i < A.length; ++i) {
            if(A[i] != A[j]) {
                j++;
                A[j] = A[i];
            }
        }
        return j + 1;
    }
}

Code (C++):

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int j = 0;
        if(n == 0)
            return 0;
        for(int i = 1; i < n; ++i) {
            if(A[i] != A[j]) {
                j++;
                A[j] = A[i];
            }
        }
        return j + 1;
    }
};
Advertisements

5 Comments (+add yours?)

  1. Trackback: (Remove Duplicates from Sorted List) « Runhe Tian Coding Practice
  2. funny
    Apr 26, 2013 @ 07:50:43

    cant able to display output in java code,even i added main method in that code

    Reply

  3. Jing
    Feb 06, 2014 @ 17:01:53

    Thanks for the brilliant solution. The Java code is correct, which is only code I looked at.

    Reply

  4. mjava
    Feb 15, 2014 @ 23:29:48

    Java code is not correct; Gave input {22, 22, 44, 55, 77, 99, 99,122} and got output as {22, 44, 55, 77, 99, 122, 99, 122}.

    Reply

  5. mjava
    Feb 16, 2014 @ 01:49:29

    Correct version of program is :

    public void noDups() {
    int left_comp = 0;
    int right_comp = 1;
    boolean start_move = false;
    int hole = 0;

    for(; right_comp <nElems;right_comp++,left_comp++) {
    if(a[left_comp] == a[right_comp]){
    if(!start_move){
    start_move = true;
    hole = right_comp;
    }
    }
    else if(start_move){
    a[hole++] = a[right_comp];
    }
    }

    for(;hole<nElems;hole++){
    a[hole] = 0;
    }
    }

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: