![]() |
VOOZH | about |
Given an array that contains all elements occurring k times, but one occurs only once. Find that unique element.
Examples:
Input : arr[] = {6, 2, 5, 2, 2, 6, 6}
k = 3
Output : 5
Explanation: Every element appears 3 times accept 5.Input : arr[] = {2, 2, 2, 10, 2}
k = 4
Output: 10
Explanation: Every element appears 4 times accept 10.
A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present k times or not. If present, then ignores the element, else prints the element.
The Time Complexity of the above solution is O(n2). We can Use Sorting to solve the problem in O(nLogn) time. The idea is simple, the first sort the array so that all occurrences of every element become consecutive. Once the occurrences become consecutive, we can traverse the sorted array and print the unique element in O(n) time.
We can Use Hashing to solve this in O(n) time on average. The idea is to traverse the given array from left to right and keep track of visited elements in a hash table. Finally, print the element with count 1.
The hashing-based solution requires O(n) extra space. We can use bitwise AND to find the unique element in O(n) time and constant extra space.
Below is the implementation of the above approach:
5
Time Complexity:O(n)
Auxiliary Space: O(1)
This article is contributed by Dhiman Mayank.
Approach:
In this approach, we create two sets: one to store the unique elements in the array, and the other to store the elements that appear k times. Then we return the difference between these two sets.
5
Time Complexity: O(n)
Space Complexity: O(n)