707278. Unique Number III

Medium

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:

  1. Initialize an integer variable result set to 0.
  2. Iterate through each element x in 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 result with the calculated value.
  3. The final value of result will 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

View on GeeksforGeeks
public int findElement(int[] arr) {
    int result = 0;
    for (int x : arr) {
        result ^= x;
    }
    return result;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.