Open In App

Find the only non-repeating element in a given array

Last Updated : 04 Nov, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

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

  1. Traverse the array
  2. Use an Unordered Map to store the frequency of array elements.
  3. Traverse the Map and find the element with frequency 1 and print that element.

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
2

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++
Java Python3 C# JavaScript

Output
2

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++
Java Python3 C# JavaScript

Output
2

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


Next Article
Practice Tags :

Similar Reads