Unique element in an array where all elements occur k times except one
Last Updated :
07 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.
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.
- Create an array count[] of size equal to number of bits in binary representations of numbers.
- Fill count array such that count[i] stores count of array elements with i-th bit set.
- 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:
C++
// CPP program to find unique element where
// every element appears k times except one
#include <bits/stdc++.h>
using namespace std;
int findUnique(unsigned int a[], int n, int k)
{
// Create a count array to store count of
// numbers that have a particular bit set.
// count[i] stores count of array elements
// with i-th bit set.
int INT_SIZE = 8 * sizeof(unsigned int);
int count[INT_SIZE];
memset(count, 0, sizeof(count));
// AND(bitwise) each element of the array
// with each set digit (one at a time)
// to get the count of set bits at each
// position
for (int i = 0; i < INT_SIZE; i++)
for (int j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
// Now consider all bits whose count is
// not multiple of k to form the required
// number.
unsigned res = 0;
for (int i = 0; i < INT_SIZE; i++)
res += (count[i] % k) * (1 << i);
// Before returning the res we need
// to check the occurrence of that
// unique element and divide it
res = res / (n % k);
return res;
}
// Driver Code
int main()
{
unsigned int a[] = { 6, 2, 5, 2, 2, 6, 6 };
int n = sizeof(a) / sizeof(a[0]);
int k = 3;
cout << findUnique(a, n, k);
return 0;
}
Java
// Java program to find unique element where
// every element appears k times except one
class GFG {
static int findUnique(int a[], int n, int k)
{
// Create a count array to store count of
// numbers that have a particular bit set.
// count[i] stores count of array elements
// with i-th bit set.
byte sizeof_int = 4;
int INT_SIZE = 8 * sizeof_int;
int count[] = new int[INT_SIZE];
// AND(bitwise) each element of the array
// with each set digit (one at a time)
// to get the count of set bits at each
// position
for (int i = 0; i < INT_SIZE; i++)
for (int j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
// Now consider all bits whose count is
// not multiple of k to form the required
// number.
int res = 0;
for (int i = 0; i < INT_SIZE; i++)
res += (count[i] % k) * (1 << i);
// Before returning the res we need
// to check the occurrence of that
// unique element and divide it
res = res / (n % k);
return res;
}
// Driver Code
public static void main(String[] args)
{
int a[] = { 6, 2, 5, 2, 2, 6, 6 };
int n = a.length;
int k = 3;
System.out.println(findUnique(a, n, k));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program to find unique element where
# every element appears k times except one
import sys
def findUnique(a, n, k):
# Create a count array to store count of
# numbers that have a particular bit set.
# count[i] stores count of array elements
# with i-th bit set.
INT_SIZE = 8 * sys.getsizeof(int)
count = [0] * INT_SIZE
# AND(bitwise) each element of the array
# with each set digit (one at a time)
# to get the count of set bits at each
# position
for i in range(INT_SIZE):
for j in range(n):
if ((a[j] & (1 << i)) != 0):
count[i] += 1
# Now consider all bits whose count is
# not multiple of k to form the required
# number.
res = 0
for i in range(INT_SIZE):
res += (count[i] % k) * (1 << i)
# Before returning the res we need
# to check the occurrence of that
# unique element and divide it
res = res / (n % k)
return res
# Driver Code
if __name__ == '__main__':
a = [6, 2, 5, 2, 2, 6, 6]
n = len(a)
k = 3
print(findUnique(a, n, k))
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find unique element where
// every element appears k times except one
using System;
class GFG {
static int findUnique(int[] a, int n, int k)
{
// Create a count array to store count of
// numbers that have a particular bit set.
// count[i] stores count of array elements
// with i-th bit set.
byte sizeof_int = 4;
int INT_SIZE = 8 * sizeof_int;
int[] count = new int[INT_SIZE];
// AND(bitwise) each element of the array
// with each set digit (one at a time)
// to get the count of set bits at each
// position
for (int i = 0; i < INT_SIZE; i++)
for (int j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
// Now consider all bits whose count is
// not multiple of k to form the required
// number.
int res = 0;
for (int i = 0; i < INT_SIZE; i++)
res += (count[i] % k) * (1 << i);
// Before returning the res we need
// to check the occurrence of that
// unique element and divide it
res = res / (n % k);
return res;
}
// Driver Code
public static void Main(String[] args)
{
int[] a = { 6, 2, 5, 2, 2, 6, 6 };
int n = a.Length;
int k = 3;
Console.WriteLine(findUnique(a, n, k));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to find unique element where
// every element appears k times except one
function findUnique(a, n, k)
{
// Create a count array to store count of
// numbers that have a particular bit set.
// count[i] stores count of array elements
// with i-th bit set.
let sizeof_let = 4;
let LET_SIZE = 8 * sizeof_let;
let count = Array.from({length: LET_SIZE}, (_, i) => 0);
// AND(bitwise) each element of the array
// with each set digit (one at a time)
// to get the count of set bits at each
// position
for (let i = 0; i < LET_SIZE; i++)
for (let j = 0; j < n; j++)
if ((a[j] & (1 << i)) != 0)
count[i] += 1;
// Now consider all bits whose count is
// not multiple of k to form the required
// number.
let res = 0;
for (let i = 0; i < LET_SIZE; i++)
res += (count[i] % k) * (1 << i);
// Before returning the res we need
// to check the occurrence of that
// unique element and divide it
res = res / (n % k);
return res;
}
// driver function
let a = [ 6, 2, 5, 2, 2, 6, 6 ];
let n = a.length;
let k = 3;
document.write(findUnique(a, n, k));
</script>
PHP
<?php
//PHP program to find unique element where
// every element appears k times except one
function findUnique($a, $n, $k)
{
// Create a count array to store count of
// numbers that have a particular bit set.
// count[i] stores count of array elements
// with i-th bit set.
$INT_SIZE = 8 * PHP_INT_SIZE;
$count = array();
for($i=0; $i< $INT_SIZE; $i++)
$count[$i] = 0;
// AND(bitwise) each element of the array
// with each set digit (one at a time)
// to get the count of set bits at each
// position
for ( $i = 0; $i < $INT_SIZE; $i++)
for ( $j = 0; $j < $n; $j++)
if (($a[$j] & (1 << $i)) != 0)
$count[$i] += 1;
// Now consider all bits whose count is
// not multiple of k to form the required
// number.
$res = 0;
for ($i = 0; $i < $INT_SIZE; $i++)
$res += ($count[$i] % $k) * (1 << $i);
// Before returning the res we need
// to check the occurrence of that
// unique element and divide it
$res = $res / ($n % $k);
return $res;
}
// Driver Code
$a = array( 6, 2, 5, 2, 2, 6, 6 );
$n = count($a);
$k = 3;
echo findUnique($a, $n, $k);
// This code is contributed by Rajput-Ji
?>
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).
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Function to find a unique element with a specified frequency (k)
int findUniqueElement(int arr[], int n, int k) {
unordered_map<int, int> freqMap; // Create an unordered_map to store frequency
// Populate the frequency map
for (int i = 0; i < n; i++) {
int num = arr[i];
freqMap[num]++; // Increment the frequency of the current element
}
// Iterate through the frequency map
for (const auto& entry : freqMap) {
if (entry.second != k) { // If the frequency is not equal to k
return entry.first; // Return the unique element
}
}
return -1; // Return -1 if no unique element is found
}
int main() {
int arr[] = {6, 2, 5, 2, 2, 6, 6};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 3;
int uniqueElement = findUniqueElement(arr, n, k);
if (uniqueElement != -1) {
cout << "Unique element: " << uniqueElement << endl;
} else {
cout << "No unique element found." << endl;
}
return 0;
}
Java
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int findUniqueElement(int[] arr, int k) {
Map<Integer, Integer> freqMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int num = arr[i];
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
if (entry.getValue() != k) {
return entry.getKey();
}
}
return -1; // or any suitable default value to indicate no unique element found
}
public static void main(String[] args) {
int[] arr = {6, 2, 5, 2, 2, 6, 6};
int k = 3;
int uniqueElement = findUniqueElement(arr, k);
if (uniqueElement != -1) {
System.out.println("Unique element: " + uniqueElement);
} else {
System.out.println("No unique element found.");
}
}
}
Python3
from collections import Counter
def find_unique_element(arr, k):
freq_dict = Counter(arr)
for key, val in freq_dict.items():
if val != k:
return key
# example usage
arr = [6, 2, 5, 2, 2, 6, 6]
k = 3
print(find_unique_element(arr, k))
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to find a unique element with a specified frequency (k)
static int FindUniqueElement(int[] arr, int k)
{
Dictionary<int, int> freqMap = new Dictionary<int, int>(); // Create a Dictionary to store frequency
// Populate the frequency map
foreach (int num in arr)
{
if (freqMap.ContainsKey(num))
{
freqMap[num]++; // Increment the frequency of the current element
}
else
{
freqMap[num] = 1; // Initialize the frequency of the current element
}
}
// Iterate through the frequency map
foreach (var entry in freqMap)
{
if (entry.Value != k) // If the frequency is not equal to k
{
return entry.Key; // Return the unique element
}
}
return -1; // Return -1 if no unique element is found
}
static void Main()
{
int[] arr = { 6, 2, 5, 2, 2, 6, 6 };
int k = 3;
int uniqueElement = FindUniqueElement(arr, k);
if (uniqueElement != -1)
{
Console.WriteLine("Unique element: " + uniqueElement);
}
else
{
Console.WriteLine("No unique element found.");
}
}
}
JavaScript
// Function to find a unique element with a specified frequency (k)
function findUniqueElement(arr, k) {
let freqMap = new Map(); // Create a Map to store frequency
// Populate the frequency map
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
if (freqMap.has(num)) {
freqMap.set(num, freqMap.get(num) + 1); // Increment the frequency of the current element
} else {
freqMap.set(num, 1);
}
}
// Iterate through the frequency map
for (const [key, value] of freqMap) {
if (value !== k) { // If the frequency is not equal to k
return key; // Return the unique element
}
}
return -1; // Return -1 if no unique element is found
}
const arr = [6, 2, 5, 2, 2, 6, 6];
const k = 3;
const uniqueElement = findUniqueElement(arr, k);
if (uniqueElement !== -1) {
console.log("Unique element:", uniqueElement);
} else {
console.log("No unique element found.");
}
Time Complexity: O(n)
Space Complexity: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem