VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-unique-element-element-occurs-k-times-except-one/

⇱ Unique element in an array where all elements occur k times except one - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unique element in an array where all elements occur k times except one

Last Updated : 7 Nov, 2023

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.

Recommended Practice

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. 

  1. Create an array count[] of size equal to number of bits in binary representations of numbers.
  2. Fill count array such that count[i] stores count of array elements with i-th bit set.
    1. Form result using count array. We put 1 at a position i in result if count[i] is not multiple of k. Else we put 0.

Below is the implementation of the above approach:


Output
5

Time Complexity:O(n)
Auxiliary Space: O(1)

This article is contributed by Dhiman Mayank.  

Using Set:

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.

  • Create two empty sets: unique_set and k_set.
  • Iterate through each element in the array arr.
  • If the element is already in the unique_set, it means it has appeared before. Add it to k_set.
  • If the element is not in the unique_set, add it to unique_set.
  • Take the set difference between unique_set and k_set using the - operator. This gives us a set with only the unique element in it.
  • Use the pop() method to get the element from the set (since there is only one element in it).

Output
5

Time Complexity: O(n)
Space Complexity: O(n)

Comment
Article Tags: