Finding duplicates in a list using recursion?

Posted by user1760892 on Stack Overflow See other posts from Stack Overflow or by user1760892
Published on 2012-10-24T16:42:58Z Indexed on 2012/10/24 17:00 UTC
Read the original article Hit count: 228

Filed under:
|
|

I'm suppose to find if there is duplicates in a list and return true or false using recursion only (no loops). So if ArrayList of char is used, [a,b,c,d,e] should return false. [a,a,b,c,d] or [a,b,b,c,c,d] should return true. I've tried and tested different ways and it worked for some cases but not all. I changed my code around and this is what I have now. (Has problem at the last if statement) Can anyone give me some hints? Thanks.

    public static <T> boolean duplicate(List<T> list) throws NullPointerException {
        return duplicateHelper(list, list.get(0));
}

public static <T> boolean duplicateHelper(List<T> list, T t){
    if (list == null)
        throw new NullPointerException();
    if(list.isEmpty())
        return false;
    if(list.size() > 1){
        if(t.equals(list.get(1)))
            return true;        
    }
    if(list.size() == 1)
        return false;
    if(!duplicateHelper(list.subList(1,list.size()), t)){
        return  duplicate(list.subList(1,list.size()));
    }
    return false;

}

© Stack Overflow or respective owner

Related posts about java

Related posts about list