-1

I'm trying to remove duplicates from the array, but it is not working.

Am I missing something ?

Code :-

class RemoveStringDuplicates {

    public static char[] removeDups(char[] str) {
        boolean bin_hash[] = new boolean[256];
        int ip_ind = 0, res_ind = 0;
        char temp;

        while (ip_ind < str.length) {
            temp = str[ip_ind];
            if (bin_hash[temp] == false) {
                bin_hash[temp] = true;
                str[res_ind] = str[ip_ind];
                res_ind++;
            }
            ip_ind++;
        }

        return str;
    }

    public static void main(String[] args) {
        char str[] = "test string".toCharArray();
        System.out.println(removeDups(str));
    }
}

Output :-

 tes ringing //ing should not have been repeated!
5
  • You are using the java language wrong. Jul 14, 2013 at 19:00
  • @AJMansfield. Well true. But not all start using a language the way it is supposed to be used from the very beginning. So, probably OP will learn the usage of libraries gradually.
    – Rohit Jain
    Jul 14, 2013 at 19:01
  • @RohitJain Problems like these should not be given to classes that are not then taught (or haven't already been taught) how to solve them correctly. Jul 14, 2013 at 19:06
  • 1
    @AJMansfield. You won't appreciate the correct way of doing things much, if you haven't already used the incorrect way to solve the same problem.
    – Rohit Jain
    Jul 14, 2013 at 19:09
  • @RohitJain I guess you're right. Jul 14, 2013 at 19:10

6 Answers 6

2

Instead of assigning the characters into the same array, you should use a new array. Because, after removing the duplicates, the trailing elements are not being removed, and thus are printed.

So, if you use a new array, the trailing elements would be null characters.

So, just create an new array:

char[] unique = new char[str.length];

And then change the assignment:

str[res_ind] = str[ip_ind];

to:

unique[res_ind] = str[ip_ind];

Also, you can consider using an ArrayList instead of an array. That way you won't have to maintain a boolean array for each character, which is quite too much. You are loosing some not-needed extra space. With an ArrayList, you can use the contains method to check for the characters already added.

Well, you can also avoid doing all those counting stuffs manually, by using a Set, which automatically removes duplicates for you. But most implementation does not maintain insertion order. For that you can use LinkedHashSet.

2
  • Actually, about your second point. LinkedHashSet maintains insertion order. Jul 14, 2013 at 19:09
  • @AnthonyAccioly. Oh! yeah missed it. Will add to the answer.
    – Rohit Jain
    Jul 14, 2013 at 19:10
1

The specific problem has already found a solution, but if you are not restricited to using your own method and can use the java libraries, I would suggest something like this:

public class RemoveDuplicates {

// Note must wrap primitives for generics
// Generic array creation not supported by java, gotta return a list

public static <T> List<T> removeDuplicatesFromArray(T[] array) {
    Set<T> set = new LinkedHashSet<>(Arrays.asList(array));
    return new ArrayList<>(set);
}

public static void main(String[] args) {
    String s = "Helloo I am a string with duplicates";
    Character[] c = new Character[s.length()];

    for (int i = 0; i < s.length(); i++) {
        c[i] = s.charAt(i);
    }

    List<Character> noDuplicates = removeDuplicatesFromArray(c);
    Character[] noDuplicatesArray = new Character[noDuplicates.size()];
    noDuplicates.toArray(noDuplicatesArray);

    System.out.println("List:");
    System.out.println(noDuplicates);
    System.out.println("\nArray:");
    System.out.println(Arrays.toString(noDuplicatesArray));
}
}

Out:

List:
[H, e, l, o,  , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]

Array:
[H, e, l, o,  , I, a, m, s, t, r, i, n, g, w, h, d, u, p, c]

The linkedhashset retains ordering, which might be especially important for things like characterarrays.

0

Try This:

public static char[] removeDups(char[] str) {
        boolean bin_hash[] = new boolean[256];
        int ip_ind = 0, res_ind = 0;
        char temp;
        char a[] = new char[str.length];

        while (ip_ind < str.length) {
            temp = str[ip_ind];
            if (bin_hash[temp] == false) {
                bin_hash[temp] = true;
                a[res_ind] = str[ip_ind];
                res_ind++;
            }
            ip_ind++;
        }

        return a;
    }

You basically are updating the str variable in the loop. Updating it and again looping on the updated array.

0

I believe the problem is caused by the fact that you are iterating over str while you are modifying it (by the line str[res_ind] = str[ip_ind]). If you copy the result to another array, it works:

class RemoveStringDuplicates {

    public static char[] removeDups(char[] str) {
        char result[] = new char[str.length];
        boolean bin_hash[] = new boolean[256];
        int ip_ind = 0, res_ind = 0;
        char temp;

        while (ip_ind < str.length) {
            temp = str[ip_ind];
            if (bin_hash[temp] == false) {
                bin_hash[temp] = true;
                result[res_ind] = str[ip_ind];
                res_ind++;
            }
            ip_ind++;
        }

        return result;
    }

    public static void main(String[] args) {
        char str[] = "test string".toCharArray();
        System.out.println(removeDups(str));
    }
}
0

All the other answers seem to be correct. The "ing" that you see at the end of the result is actually untouched characters already in the array.

As an alternative solution (if you want to conserve memory), you can loop over the last part of the array to delete the characters at the end because you already know they are duplicate.

//C# code, I think you just need to change str.Length here to str.length
for (int delChars = res_ind; delChars < str.Length; delChars++)
{
    str[delChars] = '\0';
}
0

You are totally abusing the Java language with your code. The data structure classes in the standard libraries are the main point of using Java. Use them.

The correct way to code something to do what you want is here:

class RemoveStringDuplicates {

    public static String removeDups(CharSequence str) {

        StringBuilder b = new StringBuilder(str);
        HashSet<Character> s = new HashSet<Character>();

        for(int idx = 0; idx < b.size(); idx++)
            if(mySet.contains(b.charAt(idx)))
                b.deleteCharAt(idx--);
            else
                s.add(ch);

        return b.toString();
    }

    public static void main(String[] args) {
        System.out.println(removeDups(str));
    }
}

There are probably even better ways of doing it, too. Don't go avoiding Java's data structures.

If you are writing code that is performance-sensitive enough that you have to use primitive code like that in your question, you should be using a different language, like C.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.