#283 Finding the Index of the First Duplicate

Companies:
Gazprombank Itone
Themes:
AlgorithmsArraysPractice

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.

Java
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

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in