707278. Unique Number III
Find Element Occurring Once When All Other Are Present Thrice
Slug: find-element-occuring-once-when-all-other-are-present-thrice
Difficulty: Medium
Id: 707278
Topic Tags: Arrays, Mathematical, Bit Magic, Data Structures, Algorithms
Company Tags: Google
Summary
Given an array of integers where all elements are present thrice except one which is present only once. Find that single element.
The problem involves bit manipulation and array processing, making it a classic example of using bitwise operations to solve a problem efficiently.
Detailed Explanation
Let's first consider the given array arr of length n. As per the problem statement, all elements are present thrice except one which is present only once. This means that for every element x in the array, it appears three times at positions i, j, and k.
Our goal is to find this unique element.
Here's a step-by-step breakdown of the solution:
- Initialize an integer variable
resultset to 0. - Iterate through each element
xin the array:- For each
x, calculate its bitwise XOR with all other elements in the array using the following formula:x ^ (arr[0] + arr[1] + ... + arr[n-1]) - Update
resultwith the calculated value.
- For each
- The final value of
resultwill be the unique element that appears only once.
Time Complexity Analysis: The time complexity of this solution is O(n), where n is the length of the array. This is because we are iterating through each element in the array once.
Space Complexity Analysis:
The space complexity of this solution is O(1), as we are using a constant amount of space to store the result variable.
Optimized Solutions
Java
public int findElement(int[] arr) {
int result = 0;
for (int x : arr) {
result ^= x;
}
return result;
}