0

Please read the question before marking it as duplicate

I have written following code to remove duplicates from array without using Util classes but now I am stuck

public class RemoveDups{
    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };

        int temp;
        for (int i : a) {
            for (int j = 0; j < a.length - 1; j++) {
                if (a[j] > a[j + 1]) {
                    temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
        a = removeDups(a);
        for (int i : a) {
            System.out.println(i);
        }

    }

    private static int[] removeDups(int[] a) {
        int[] result = new int[a.length];
        int j = 0;
        for (int i : a) {
            if (!isExist(result, i)) {
                result[j++] = i;
            }
        }

        return result;
    }

    private static boolean isExist(int[] result, int i) {
        for (int j : result) {
            if (j == i) {
                return true;
            }
        }
        return false;
    }

}

and now the output is

1
2
3
4
5
6
45
52
0
0
0
0
0
0
0
0
0
0

Here my problem is

  1. My code is not working in case of 0s
  2. I am not able to understand how sorting an array can reduce time of execution
  3. Is there any way to remove elements from array without using Util classes I know one way to remove convert array into list and then remove but for that also we need Util classes is there any way to implement by myself.
6
  • Is the range of the input numbers limited in some way? For example 0-10000 Commented Oct 4, 2013 at 6:52
  • yes we can assume that Commented Oct 4, 2013 at 6:53
  • @javaBeginner sorry for that sentence but the problem is I dont want to be blocked from asking questions and this question seems duplicate of many questions Commented Oct 4, 2013 at 7:00
  • 1
    You can sort the arrays first and then use your code. Track the last index of the data you are replacing and use System.arrayCopy() to copy to a different array. Also using that index you can define a new array and copy the data from your created array till you get a zero. But I seriously think you should use the util classes for this purpose. Commented Oct 4, 2013 at 7:02
  • 1
    @ankit Have you considered this kind of solution (might be sligthly adapted to your case) ? codereview.stackexchange.com/questions/98383/… Commented Sep 4, 2015 at 14:13

7 Answers 7

3

Since the numbers you deal with are limited to a small range you can remove duplicates by a simple "counting sort": mark the numbers you have found in a set-like data structure and then go over the data structure. An array of boolean works just fine, for less memory usage you could create a basic bitset or hash table. If n is the number of elements in the array and m is the size of the range, this algorithm will have O(n+m) complexity.

private static int[] removeDups(int[] a, int maxA) {
    boolean[] present = new boolean[maxA+1];
    int countUnique = 0;
    for (int i : a) {
        if (!present[i]) {
            countUnique++;
            present[i] = true;
        }
    }

    int[] result = new int[countUnique];
    int j = 0;
    for (int i=0; i<present.length; i++) {
        if (present[i]) result[j++] = i;
    }

    return result;
}

I am not able to understand how sorting an array can reduce time of execution

In a sorted array you can detect duplicates in a single scan, taking O(n) time. Since sorting is faster than checking each pair - O(n log n) compared to O(n²) time complexity - it would be faster to sort the array instead of using the naive algorithm.

Sign up to request clarification or add additional context in comments.

Comments

2
  1. As you are making the result array of the same length as array a so even if you put only unique items in it, rest of the blank items will have the duplicate values in them which is 0 for int array.
  2. Sorting will not help you much, as you code is searching the whole array again and again for the duplicates. You need to change your logic for it.
  3. You can put some negative value like -1 for all the array items first in result array and then you can easily create a new result array say finalResult array from it by removing all the negative values from it, It will also help you to remove all the zeroes.

Comments

2

In java , arrays are of fixed length. Once created, their size can't be changed. So you created an array of size18. Then after you applied your logic , some elements got deleted. But array size won't change. So even though there are only 8 elements after the duplicate removal, the rest 10 elements will be auto-filled with 0 to keep the size at 18.

Solution ?

  1. Store the new list in another array whose size is 8 ( or whatever, calculate how big the new array should be)
  2. Keep a new variable to point to the end of the last valid element, in this case the index of 52. Mind you the array will still have the 0 values, you just won't use them.

I am not able to understand how sorting an array can reduce time of execution What ? You sort an array if you need it to be sorted. Nothing else. Some algorithm may require the array to be sorted or may work better if the array is sorted. Depends on where you are using the array. In your case, the sorting will not help.

As for your final question , you can definitely implement your own duplicate removal by searching if an element exists more than once and then deleting all the duplicates.

Comments

1

My code is not working in case of 0

There were no zeroes to begin with in your array. But because its an int[], after the duplicates are removed the remaining of the indexes are filled with 0. That's why you can see a lot of zeroes in your array. To get rid of those 0s, you need to create another array with a lesser size(size should be equal to the no. of unique numbers you've in your array, excluding 0).

If you can sort your array(I see that its already sorted), then you could either bring all the zeroes to the front or push them to the last. Based on that, you can iterate the array and get the index from where the actual values start in the array. And, then you could use Arrays.copyOfRange(array, from, to) to create a copy of the array only with the required elements.

3 Comments

reason I know why I am getting zeros but my problem is I want to remove those 0s as well
You have already sorted, so you needn't sort again. All you need to do is figure out the index from where the 0s start and make a copy of your array from the start index to the indexOfZero-1.
If I true understand, 'java.util' package cannot be used, but System.arrayCopy can. In fact, Array.copyOfRange call inside System.arrayCopy.
0

try this

 package naveed.workingfiles;



public class RemoveDups {
    public static void main(String[] args) {
        int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45, };
        removeDups(a);
    }

private static void removeDups(int[] a) {
    int[] result = new int[a.length];
    int j = 0;
    int count = 0;
    for (int i : a) {
        if (!isExist(result, i)) {
            result[j++] = i;
            count++;
        }
    }
    System.out.println(count + "_____________");
    for (int i=0;i<count;i++) {
        System.out.println(result[i]);
    }

    // return result;
}

private static boolean isExist(int[] result, int i) {
    for (int j : result) {
        if (j == i) {
            return true;
        }
    }
    return false;
}

}

2 Comments

I am not allowed to use Util classes
good solution but this will not work in case of 0 if array has one or more 0s it will not work rest is fine
0
public class RemoveDups {
    public static void main(String[] args) {
        int[] a = { 1, 2, 0, 3, 1,0, 3, 6, 2};
        removeDups(a);
    }

private static void removeDups(int[] a) {
    int[] result = new int[a.length];
    int j = 0;
    int count = 0;
    boolean zeroExist = false;
    for (int i : a) {
        if(i==0 && !zeroExist){
            result[j++] = i;
            zeroExist = true;
            count++;
        }
        if (!isExist(result, i)) {
            result[j++] = i;
            count++;
        }
    }
    System.out.println(count + "_____________");
    for (int i=0;i<count;i++) {
        System.out.println(result[i]);
    }

    // return result;
}

private static boolean isExist(int[] result, int i) {

    for (int j : result) {
        if (j == i) {
            return true;
        }
    }
    return false;
}
}
// It works even Array contains 'Zero'

2 Comments

Please don’t just post code as an answer. Add some explanation what it does.
Sure Mary! Simply identifying whether the original array contains Zero or not. If it contains adding to the result array. To avoid duplicates maintaining "zeroExist" boolean flag. I just enhanced the below exiting post by @ khAn
-1
class Lab2 {
public static void main(String[] args) {
    int[] a = { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 3, 1, 4, 52, 1, 45 };
    removeDups(a);
}

private static void removeDups(int[] a) {
    int[] result = new int[a.length];
    int j = 0;
    int count = 0;
    for (int i : a) {
        if (!isExist(result, i)) {
            result[j++] = i;
            count++;
        }
    }
    System.out.println(count + "_____________");
    for (int i = 0; i < count; i++) {
        System.out.println(result[i]);
    }
}

private static boolean isExist(int[] result, int i) {
    for (int j : result) {
        if (j == i) {
            return true;
        }
    }
    return false;
}
}

1 Comment

This is not a good answer. You provide code exclusively, which is considered bad on Stack Overflow. You should extend your answer and add some explanations to your code. Beside that, you don't give an answer to all aspects of the question. Part 1 and part 2 are not covered in your answer. Maybe you want to add that, too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.