This isn't a good use case for recursion, which leads me to wonder what the point of the problem is. However, it's worth noting that LISP programmers (from what I've observed) traditionally used recursion for everything; early versions of the language may not have had any kind of loop construct. When programming in this way, one gets used to figuring out how to use recursion for an algorithm that would be a loop in any other language.
The main technique, I think, is to figure out what running local variables you'll need to keep, and pass them as parameters to a recursive helper function.
To solve this problem with a loop, I'd define a Set
that is initially empty. As I go through the array, I'd: (1) see if the array element is already in the set, and return true
if it is; (2) add the element to the set.
Here, the Set
is the running variable that you need to keep. The array index is another "running variable". (In classic LISP, you'd just use a cdr
function that means "the rest of the list", so you wouldn't need to maintain an index; I don't think that's easy to do with a Java ArrayList
.) So you'll want a recursive method that has a Set
and a "current index" as a parameter:
private boolean hasDuplicateHelper(ArrayList<Integer> a, int currentIndex, Set<Integer> alreadySeen) { ... }
The outer method will initialize the set to an empty set and call the helper with it this set, and with 0 as the current index. The recursive method will (1) look at the current element and see if it's in alreadySeen
and return true
if it is; (2) add the current element to the set; (3) call the method recursively with the new set as the alreadySeen
parameter, and with the appropriate new value for the current index (I'll let you figure that one out).
I'll leave it to you to work out the rest of the details, such as how to stop.
EDIT: Now that it's clear from the comments that the desired result is to print the duplicate values instead of just "yes" or "no", something will have to change. But I think this can be done just by changing the method result to a Set<Integer>
that contains a set of all the duplicates. If more information is needed, such as the indexes where the duplicates occur or the number of times each duplicate occurs, a different result structure may have to be used.