VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-element-appears-array-every-element-appears-twice/

⇱ Unique Number I - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unique Number I

Last Updated : 25 Apr, 2026

Given an array of integers, every element in the array appears twice except for one element which appears only once. The task is to identify and return the element that occurs only once.

Examples: 

Input:  arr[] = [2, 3, 5, 4, 5, 3, 4]
Output:
Explanation: Since 2 occurs once, while other numbers occur twice, 2 is the answer.

Input: arr[] = [2, 2, 5, 5, 20, 30, 30]
Output: 20
Explanation: Since 20 occurs once, while other numbers occur twice, 20 is the answer.

[Naive Approach] Nested Loop Frequency Counting - O(n^2) Time and O(1) Space

This approach iterates through the array and counts the frequency of each element using a nested loop. For each element, the inner loop counts how many times it appears in the array. If an element appears exactly once, it is returned as the result. This method ensures that the correct element is identified but is inefficient due to the nested loop.


Output
2

[Better Approach] Using Hash Map - O(n) Time and O(n) Space

This approach uses a hash map (or dictionary) to track the frequency of each element in the array. First, we iterate through the array to record how many times each element appears. Then, we scan the hash map to find the element that appears exactly once. If such an element is found, it is returned; otherwise, the function returns -1. This method efficiently solves the problem in linear time with a linear space complexity.

Working of Approach:

  1. Traverse all elements and insert them into a hash table. Element is used as key and the frequency is used as the value in the hash table. 
  2. Iterate through the map and return the value with count equal to 1.

Output
2

[Expected Approach] Using XOR Operation - O(n) Time and O(1) Space

This approach uses the XOR operation to find the unique element in an array where every other element appears twice. XOR of two identical numbers cancels them out (results in zero), so after XORing all the elements, only the element that appears once will remain.

👁 h

Algorithm:

  • Initialize res as 0
  • Traverse the array and for each element, update: res = res ⊕ arr[i]
  • Duplicate elements cancel out in overall XOR
  • Final value of res will be the unique element

Working of Approach:

👁 arrray
👁 hg

Output
20
Comment
Article Tags: