24. Unique Number III

The problem can be found at the following link: ๐Ÿ”— Question Link

๐Ÿงฉ Problem Description

Given an array arr[] where every element occurs thrice except one element which occurs only once, your task is to find that unique element.

๐Ÿ“˜ Examples

Example 1:

Input:

arr[] = [1, 10, 1, 1]

Output:

10

Explanation:

All numbers except 10 occur three times. Hence, the answer is 10.

Example 2:

Input:

arr[] = [3, 2, 1, 34, 34, 1, 2, 34, 2, 1]

Output:

3

Explanation:

Only 3 occurs once. All other numbers appear exactly three times.

๐Ÿ”’ Constraints

  • $( 1 \leq \text{arr.size()} \leq 10^5 )$

  • $( \text{arr.size()}$ % 3 = 1 )

  • $( -10^9 \leq \text{arr[i]} \leq 10^9 )$

โœ… My Approach:

Optimized Bitwise Counting

This method uses bitwise manipulation to keep track of bits appearing once, twice, and thrice across the array.

Algorithm Steps:

  1. Initialize two variables ones and twos to 0.

  2. For each element:

    • Update ones as: (ones ^ num) & ~twos

    • Update twos as: (twos ^ num) & ~ones

  3. After the loop, ones will hold the element that appears only once.

๐Ÿงฎ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(N), since we iterate once through the array.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant number of variables.

๐Ÿง  Code (C++)

class Solution {
  public:
    int getSingle(vector<int> &arr) {
        int ones = 0, twos = 0;
        for (int num : arr) {
            ones = (ones ^ num) & ~twos;
            twos = (twos ^ num) & ~ones;
        }
        return ones;
    }
};
โšก Alternative Approaches

๐Ÿ“Š 2๏ธโƒฃ Hash Map Frequency Count

Algorithm Steps:

  1. Traverse the array and record each numberโ€™s count in an unordered_map.

  2. Iterate over the map and return the key with frequency = 1.

class Solution {
  public:
    int getSingle(vector<int>& arr) {
        unordered_map<int,int> freq;
        for (int x : arr) freq[x]++;
        for (auto &p : freq)
            if (p.second == 1)
                return p.first;
        return 0;
    }
};

๐Ÿ“ Complexity Analysis:

  • Time: O(n)

  • Space: O(n)

โœ… Why This Approach?

  • Straightforward to implement

  • Handles any distribution of frequencies, not limited to exactly three repeats

๐Ÿ“Š 3๏ธโƒฃ Sorting and Scan

Algorithm Steps:

  1. Sort the array.

  2. Scan with index i from 0 to nโˆ’1 in steps of 3:

    • If arr[i] == arr[i+1] == arr[i+2], skip these three (i += 3);

    • Else, return arr[i].

  3. If loop ends, the last element is the single one.

class Solution {
  public:
    int getSingle(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        int n = arr.size(), i = 0;
        while (i + 2 < n) {
            if (arr[i] == arr[i+1] && arr[i] == arr[i+2])
                i += 3;
            else
                return arr[i];
        }
        return arr[n-1];
    }
};

๐Ÿ“ Complexity Analysis:

  • Time: O(n log n)

  • Space: O(1) (in-place sort)

โœ… Why This Approach?

  • No extra data structures beyond sorting

  • Intuitive when you can afford the sort overhead

๐Ÿ†š Comparison of Approaches

Approach

โฑ๏ธ Time

๐Ÿ—‚๏ธ Space

โœ… Pros

โš ๏ธ Cons

Bitwise Counting

๐ŸŸข O(n)

๐ŸŸข O(1)

Fastest, constant space

Bitwise logic can be tricky

Hash Map Frequency

๐ŸŸข O(n)

๐Ÿ”ด O(n)

Easiest to implement

Extra memory for map

Sorting + Scan

๐Ÿ”ด O(n log n)

๐ŸŸข O(1)

No extra DS (in-place)

Slower due to sort

โœ… Best Choice?

Scenario

Recommended Approach

โœ… Exactly one unique, rest appear thrice

๐Ÿฅ‡ Bitwise Counting

โœ… Quick implementation, input size moderate

๐Ÿฅˆ Hash Map Frequency

โœ… Memory very tight, sorting overhead acceptable

๐Ÿฅ‰ Sorting + Scan

๐Ÿง‘โ€๐Ÿ’ป Code (Java)

class Solution {
    public int getSingle(int[] arr) {
        int ones = 0, twos = 0;
        for (int num : arr) {
            ones = (ones ^ num) & ~twos;
            twos = (twos ^ num) & ~ones;
        }
        return ones;
    }
}

๐Ÿ Code (Python)

class Solution:
    def getSingle(self, arr):
        ones = twos = 0
        for num in arr:
            ones = (ones ^ num) & ~twos
            twos = (twos ^ num) & ~ones
        return ones

๐Ÿง  Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐Ÿ“ฌ Any Questions?. Letโ€™s make this learning journey more collaborative!

โญ If you find this helpful, please give this repository a star! โญ

๐Ÿ“Visitor Count

Last updated