1. Introduction
Given a limited range array containing elements between 1 to n where n is the size of the array, the objective is to determine the duplicate element in the array. For a range array of size n with elements between 1 to n, there should ideally be no duplicates. However, if there is one duplicate, there will be one missing element as well. The challenge here is to find this duplicate.
2. Program Steps
1. Traverse the array.
2. For each element, calculate the absolute value of the element.
3. Go to the index represented by this absolute value and negate the value at that index.
4. If the value at that index is already negative, it implies the element has been visited before and is a duplicate.
3. Code Program
public class FindDuplicate {
public static int findDuplicate(int[] arr) {
int duplicate = -1;
for (int i = 0; i < arr.length; i++) {
// Get the absolute value of current element
int curAbs = Math.abs(arr[i]);
// If the value at this index is already negative, current element is a duplicate
if (arr[curAbs - 1] < 0) {
duplicate = curAbs;
break;
}
// Mark the value at this index as visited by negating it
arr[curAbs - 1] = -arr[curAbs - 1];
}
return duplicate;
}
public static void main(String[] args) {
int[] arr = { 3, 4, 1, 4, 2 };
System.out.println("The duplicate element is: " + findDuplicate(arr));
}
}
Output:
The duplicate element is: 4
4. Step By Step Explanation
1. We traverse each element of the array.
2. For the current element, we calculate its absolute value. This absolute value serves as the index (with a subtraction by 1 to make it 0-based).
3. If the value at this index in the array is already negative, it means this value (the current element) has been encountered before in our traversal. Hence, it's the duplicate element.
4. Otherwise, we mark the value at this index as 'visited' by making it negative.
5. The first number we find following this process that meets the criteria of step 3 is our duplicate.