#283 Finding the Index of the First Duplicate
The method does not always work correctly.
How can it be refactored or rewritten, and how can we verify that nothing has broken?
In the future, a similar method may be needed to find all duplicates, their indexes, and their count.
The method should work not only with int values, but also with objects.
Currently, the method returns the index of the element in the number sequence that is a duplicate.
public int findDuplicateIndex(int... numbers) {
int[] countArray = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
int current = numbers[i];
if (countArray[current] > 0) {
return i;
} else {
countArray[current] += 1;
}
}
throw new RuntimeException("Duplicate not found!");
}Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor