Given an array** arr[] **consisting of N positive numbers in the range [1, N], the task is to print the array elements which appear even number of times in the given array.
Example :
Input:_ N = 8, arr[] = {4, 4, 2, 4, 8, 2, 3, 4}_
Output:_ [2, 4]_
Explanation:_ The numbers 2 and 4 appear even number of times in the array._
Input:_ N=4, arr[] = {3, 1, 4, 4}_
Output:_ [4]_
Naive Approach: The simplest approach to solve the problem is to store the frequency of each array elements in a Hashmap and print the elements having even frequency.
Time Complexity:_ O(N), where N is the size of the given array._
Auxiliary Space:_ O(N)_
**Efficient Approach: **We can also solve this problem in constant space with the help of approach mentioned in solution 1 of article “Find duplicates in O(n) time and O(1) extra space”
Follow the below steps to solve the problem:
arr[abs(arr[i]) -1]_ = **– arr[abs(arr[i]) -1]_**
Below is the implementation of above approach:
// Java Program to implement
// the above approach
**import**
java.io.*;
**class**
Duplicates {
// Function to find the elements
// in the array having even frequency
**static**
**void**
findDuplicates(``**int**
a[],
**int**
n)
{
**int**
i, index =
0``, sign, returnSize;
**for**
(i =
0``; i < n; i++)
a[Math.abs(a[i]) -
1``]
= -a[Math.abs(a[i]) -
1``];
**for**
(i =
0``; i < n; i++) {
// If a[i] has occurred even times
**if**
(a[Math.abs(a[i]) -
1``] >
0``) {
// Mark a[abs(a[i])-1]
a[Math.abs(a[i]) -
1``]
= -a[Math.abs(a[i]) -
1``];
// Preserve the sign of a[index]
sign =
1``;
**if**
(a[index] <
0``)
sign = -``1``;
a[index++]
= sign * Math.abs(a[i]);
}
}
// Make every array element +ve
**for**
(i =
0``; i < index; i++)
a[i] = Math.abs(a[i]);
returnSize = index;
**for**
(i =
0``; i < returnSize; i++)
System.out.print(a[i] +
", "``);
}
// Driver code
**public**
**static**
**void**
main(String[] args)
{
**int**
a[] = {
1``,
1``,
1``,
3``,
1``,
2``,
8``,
2
};
findDuplicates(a,
8``);
}
}
Output:
1, 2,
Time Complexity:_ O(N)_
Auxiliary Space:_ O(1)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #mathematical #school programming #searching #frequency-counting #interview-preparation #java-hashmap #two-pointer-algorithm