Question: Given an array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space

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

When you see a questions which asked you do to sorting or task in place, it means you cannot use additional array or buffer, but using couple of variables is fine.

(Hint: Must sort the array before you remove duplicates. OK to use sort method)

public class RemoveDuplicateArray {

public static void main(String[] args) {

System.out.println("Testing with First array! ");

int a [] = {1,1, 3 ,2, 2};

method(a);

System.out.println(" ");

System.out.println("Testing with Second array! ");

int b [] = {1,1,2};

method(b);

System.out.println(" ");

System.out.println("Testing with Thiird array! ");

int [] c = { 5,5, 3, 2,2, 1, 1, 4};

method(c);

}

public static void method(int [] newArray)

{

//Write your code here

//Do not change the main

}

Expected Output:

Testing with First array!

Original Array is: 1 1 3 2 2

Original lenght of the Array is: 5

Sorted array is: 1 1 2 2 3

Without duplicate, Array is: 1 2 3

New lenght is: 3

Testing with Second array!

Original Array is: 1 1 2

Original lenght of the Array is: 3

Sorted array is: 1 1 2

Without duplicate, Array is: 1 2

New lenght is: 2

Testing with Thiird array!

Original Array is: 5 5 3 2 2 1 1 4

Original lenght of the Array is: 8

Sorted array is: 1 1 2 2 3 4 5 5

Without duplicate, Array is: 1 2 3 4 5

New lenght is: 5

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!