First of all I know there are plenty of solution related to this topic but I am unable to rectify the error in my code. I am writing one program to find the number of duplicates in a given array.
This code gave me ArrayOutOfBoundException
Code:
import java.util.Scanner;
class FindDuplicate
{
void printRepeating(int arr[], int size){
int count = 0;
for (int i = 0; i < size; i++){
if (arr[Math.abs(arr[i])] >= 0)
arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
else
count++;
}
System.out.print(count);
}
public static void main(String[] args)
{
FindDuplicate duplicate = new FindDuplicate();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = scan.nextInt();
duplicate.printRepeating(arr, arr.length);
}
}
But the similar code like this when I assign the array values directly in the code didn't gave me ArrayOutOfBoundException. Here is the code
class FindDuplicate
{
void printRepeating(int arr[], int size)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (arr[Math.abs(arr[i])] >= 0)
arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
else
count++;
}
System.out.println(count);
}
public static void main(String[] args)
{
FindDuplicate duplicate = new FindDuplicate();
int arr[] = {4, 2, 4, 5, 2, 3, 1};
int arr_size = arr.length;
duplicate.printRepeating(arr, arr_size);
}
}
I am unable to identify where the array is getting out of bound.
Somebody please help me to fix this.