Find the only non-repeating element in a given array
Last Updated :
23 Jul, 2025
Given an array A[] consisting of N (1 ? N ? 105) positive integers, the task is to find the only array element with a single occurrence.
Note: It is guaranteed that only one such element exists in the array.
Examples:
Input: A[] = {1, 1, 2, 3, 3}
Output: 2
Explanation:
Distinct array elements are {1, 2, 3}.
Frequency of these elements are {2, 1, 2} respectively.
Input : A[] = {1, 1, 1, 2, 2, 3, 5, 3, 4, 4}
Output : 5
Approach: Follow the steps below to solve the problem
- Traverse the array
- Use an Unordered Map to store the frequency of array elements.
- Traverse the Map and find the element with frequency 1 and print that element.
Below is the implementation of the above approach:
C++
// C++ implementation of the
// above approach
#include <bits/stdc++.h>
using namespace std;
// Function call to find
// element in A[] with frequency = 1
void CalcUnique(int A[], int N)
{
// Stores frequency of
// array elements
unordered_map<int, int> freq;
// Traverse the array
for (int i = 0; i < N; i++) {
// Update frequency of A[i]
freq[A[i]]++;
}
// Traverse the Map
for (int i = 0; i < N; i++) {
// If non-repeating element
// is found
if (freq[A[i]] == 1) {
cout << A[i];
return;
}
}
}
// Driver Code
int main()
{
int A[] = { 1, 1, 2, 3, 3 };
int N = sizeof(A) / sizeof(A[0]);
CalcUnique(A, N);
return 0;
}
Java
// Java implementation of the
// above approach
import java.util.*;
class GFG
{
// Function call to find
// element in A[] with frequency = 1
static void CalcUnique(int A[], int N)
{
// Stores frequency of
// array elements
HashMap<Integer,Integer> freq = new HashMap<Integer,Integer>();
// Traverse the array
for (int i = 0; i < N; i++)
{
// Update frequency of A[i]
if(freq.containsKey(A[i]))
{
freq.put(A[i], freq.get(A[i]) + 1);
}
else
{
freq.put(A[i], 1);
}
}
// Traverse the Map
for (int i = 0; i < N; i++)
{
// If non-repeating element
// is found
if (freq.containsKey(A[i])&&freq.get(A[i]) == 1)
{
System.out.print(A[i]);
return;
}
}
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 1, 1, 2, 3, 3 };
int N = A.length;
CalcUnique(A, N);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 implementation of the
# above approach
from collections import defaultdict
# Function call to find
# element in A[] with frequency = 1
def CalcUnique(A, N):
# Stores frequency of
# array elements
freq = defaultdict(int)
# Traverse the array
for i in range(N):
# Update frequency of A[i]
freq[A[i]] += 1
# Traverse the Map
for i in range(N):
# If non-repeating element
# is found
if (freq[A[i]] == 1):
print(A[i])
return
# Driver Code
if __name__ == "__main__":
A = [1, 1, 2, 3, 3]
N = len(A)
CalcUnique(A, N)
# This code is contributed by chitranayal.
C#
// C# implementation of the
// above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Function call to find
// element in []A with frequency = 1
static void CalcUnique(int []A, int N)
{
// Stores frequency of
// array elements
Dictionary<int,int> freq = new Dictionary<int,int>();
// Traverse the array
for (int i = 0; i < N; i++)
{
// Update frequency of A[i]
if(freq.ContainsKey(A[i]))
{
freq[A[i]] = freq[A[i]] + 1;
}
else
{
freq.Add(A[i], 1);
}
}
// Traverse the Map
for (int i = 0; i < N; i++)
{
// If non-repeating element
// is found
if (freq.ContainsKey(A[i]) && freq[A[i]] == 1)
{
Console.Write(A[i]);
return;
}
}
}
// Driver Code
public static void Main(String[] args)
{
int []A = { 1, 1, 2, 3, 3 };
int N = A.Length;
CalcUnique(A, N);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript implementation of the
// above approach
// Function call to find
// element in A[] with frequency = 1
function CalcUnique(A, N)
{
// Stores frequency of
// array elements
var freq = new Map();
// Traverse the array
for (var i = 0; i < N; i++) {
// Update frequency of A[i]
if(freq.has(A[i]))
{
freq.set(A[i], freq.get(A[i])+1);
}
else
{
freq.set(A[i],1);
}
}
// Traverse the Map
for (var i = 0; i < N; i++) {
// If non-repeating element
// is found
if (freq.get(A[i]) == 1) {
document.write( A[i]);
return;
}
}
}
// Driver Code
var A = [1, 1, 2, 3, 3 ];
var N = A.length;
CalcUnique(A, N);
</script>
Time Complexity : O(N)
Auxiliary Space : O(N)
Another Approach: Using Built-in Functions:
- Calculate the frequencies using Built-In function.
- Traverse the array and find the element with frequency 1 and print it.
Below is the implementation:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
// Function call to find element in A[] with frequency = 1
void CalcUnique(int A[], int N)
{
// Calculate frequency of all array elements
unordered_map<int, int> freq;
// Traverse the Array
for (int i = 0; i < N; i++)
{
// Update frequency of each array element in the map
int count = 1;
if (freq.count(A[i])) {
count = freq[A[i]];
count++;
}
freq[A[i]] = count;
}
// Traverse the Array
for (int i = 0; i < N; i++)
{
// If non-repeating element is found
if (freq[A[i]] == 1) {
cout << A[i] << endl;
return;
}
}
}
// Driver Code
int main()
{
int A[] = { 1, 1, 2, 3, 3 };
int N = sizeof(A) / sizeof(A[0]);
CalcUnique(A, N);
return 0;
}
Java
//Java code:
import java.util.Map;
import java.util.HashMap;
class Main{
// Function call to find
// element in A[] with frequency = 1
public static void CalcUnique(int A[], int N)
{
// Calculate frequency of
// all array elements
Map<Integer, Integer> freq = new HashMap<Integer, Integer>();
// Traverse the Array
for (int i=0; i<N; i++)
{
// Update frequency of each
// array element in the map
int count = 1;
if(freq.containsKey(A[i]))
{
count = freq.get(A[i]);
count++;
}
freq.put(A[i], count);
}
// Traverse the Array
for (int i=0; i<N; i++)
{
// If non-repeating element
// is found
if (freq.get(A[i]) == 1)
{
System.out.println(A[i]);
return;
}
}
}
// Driver Code
public static void main(String args[])
{
int A[] = {1, 1, 2, 3, 3};
int N = A.length;
CalcUnique(A, N);
}}
Python3
# Python 3 implementation of the
# above approach
from collections import Counter
# Function call to find
# element in A[] with frequency = 1
def CalcUnique(A, N):
# Calculate frequency of
# all array elements
freq = Counter(A)
# Traverse the Array
for i in A:
# If non-repeating element
# is found
if (freq[i] == 1):
print(i)
return
# Driver Code
if __name__ == "__main__":
A = [1, 1, 2, 3, 3]
N = len(A)
CalcUnique(A, N)
# This code is contributed by vikkycirus
C#
using System;
using System.Collections.Generic;
public class MainClass {
// Function call to find element in A[] with frequency =
// 1
static void CalcUnique(int[] A, int N)
{
// Calculate frequency of all array elements
Dictionary<int, int> freq
= new Dictionary<int, int>();
// Traverse the Array
for (int i = 0; i < N; i++) {
// Update frequency of each array element in the
// dictionary
if (freq.ContainsKey(A[i])) {
freq[A[i]]++;
}
else {
freq[A[i]] = 1;
}
}
// Traverse the Array
for (int i = 0; i < N; i++) {
// If non-repeating element is found
if (freq[A[i]] == 1) {
Console.WriteLine(A[i]);
return;
}
}
}
// Driver Code
public static void Main()
{
int[] A = { 1, 1, 2, 3, 3 };
int N = A.Length;
CalcUnique(A, N);
}
}
JavaScript
<script>
// Function call to find
// element in A[] with frequency = 1
function CalcUnique(A) {
// Calculate frequency of
// all array elements
let freq = A.reduce((acc, curr) => {
if (acc[curr]) {
acc[curr]++;
} else {
acc[curr] = 1;
}
return acc;
}, {});
// Traverse the Array
for (let i = 0; i < A.length; i++) {
// If non-repeating element
// is found
if (freq[A[i]] === 1) {
console.log(A[i]);
return;
}
}
}
// Driver Code
const A = [1, 1, 2, 3, 3];
CalcUnique(A);
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Another Approach: Using Sorting
The idea is to sort the array and find which element occurs only once by traversing the array.
Steps to implement this Approach-
- Sort the given array
- Then traverse from starting to the end of the array
- Since the array is already sorted that's why repeating element will be consecutive
- So in that whole array, we will find which element occurred only once. That is our required answer
Code-
C++
#include <bits/stdc++.h>
using namespace std;
// Function call to find single non-repeating element
void CalcUnique(int arr[], int N)
{
//Sort the Array
sort(arr,arr+N);
int temp=INT_MIN;
int count=0;
// Traverse the Array
for(int i=0;i<N;i++){
if(arr[i]==temp){count++;}
else{
if(count==1){
cout<<temp<<endl;
return;
}
temp=arr[i];
count=1;
}
}
//If yet not returned from the function then last element is the only non-repeating element
cout<<arr[N-1]<<endl;
}
// Driver Code
int main()
{
int arr[] = {1, 1, 2, 3, 3};
int N = sizeof(arr) / sizeof(arr[0]);
CalcUnique(arr, N);
return 0;
}
Java
import java.util.*;
public class Main {
// Function call to find single non-repeating element
public static void CalcUnique(int[] arr, int N) {
// Sort the Array
Arrays.sort(arr);
int temp=Integer.MIN_VALUE;
int count=0;
// Traverse the Array
for(int i=0;i<N;i++){
if(arr[i]==temp){
count++;
} else {
if(count==1){
System.out.println(temp);
return;
}
temp=arr[i];
count=1;
}
}
// If yet not returned from the function then last element is the only non-repeating element
System.out.println(arr[N-1]);
}
// Driver Code
public static void main(String[] args) {
int[] arr = {1, 1, 2, 3, 3};
int N = arr.length;
CalcUnique(arr, N);
}
}
Python3
def calc_unique(arr, N):
# Sort the array
arr.sort()
temp = None
count = 0
# Traverse the array
for i in range(N):
if arr[i] == temp:
count += 1
else:
if count == 1:
print(temp)
return
temp = arr[i]
count = 1
# If yet not returned from the function,
# then the last element is the only non-repeating element
print(arr[N-1])
# Driver Code
if __name__ == "__main__":
arr = [1, 1, 2, 3, 3]
N = len(arr)
calc_unique(arr, N)
C#
using System;
using System.Linq;
class Program
{
// Function to find the single non-repeating element
static void CalcUnique(int[] arr, int N)
{
// Sort the array
Array.Sort(arr);
int temp = int.MinValue;
int count = 0;
for (int i = 0; i < N; i++)
{
// If the current element is equal to the previous element, increase the count
if (arr[i] == temp)
{
count++;
}
else
{
// If the count is 1, it means the previous element is the non-repeating element
if (count == 1)
{
Console.WriteLine(temp);
return;
}
// Update the current element and reset the count
temp = arr[i];
count = 1;
}
}
// If not returned from the function, then the last element is the only non-repeating element
Console.WriteLine(arr[N - 1]);
}
static void Main(string[] args)
{
int[] arr = { 1, 1, 2, 3, 3 };
int N = arr.Length;
CalcUnique(arr, N);
}
}
JavaScript
// Function to find single non-repeating element
function calcUnique(arr) {
// Sort the Array
arr.sort((a, b) => a - b);
let temp = Number.MIN_SAFE_INTEGER;
let count = 0;
// Traverse the Array
for(let i = 0; i < arr.length; i++) {
if(arr[i] === temp) {
count++;
} else {
if(count === 1) {
console.log(temp);
return;
}
temp = arr[i];
count = 1;
}
}
// If not returned from the function yet, then the last element is the only non-repeating element
console.log(arr[arr.length - 1]);
}
// Driver Code
const arr = [1, 1, 2, 3, 3];
calcUnique(arr);
Time Complexity: O(NlogN)+O(N)=O(NlogN), O(NlogN) in sorting and O(N) in traversing the array
Auxiliary Space: O(1), because no extra space has been taken
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