![]() |
VOOZH | about |
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: 2
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.
Table of Content
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.
2
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:
2
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.
Algorithm:
Working of Approach:
20