#3158

Find the XOR of Numbers Which Appear Twice

Easy
ArrayHash TableBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Using a HashMap allows us to count occurrences of each number in a single pass, making it more efficient. We can then XOR the numbers that appear twice in another pass.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a HashMap to count occurrences of each number.
  2. 2Step 2: Loop through the array and populate the HashMap with counts.
  3. 3Step 3: Initialize a variable `result` to 0 for the XOR of numbers that appear twice.
  4. 4Step 4: Loop through the HashMap and XOR the keys (numbers) that have a count of 2.
  5. 5Step 5: Return `result`.
solution.py9 lines
1def findXOR(nums):
2    count_map = {}
3    for num in nums:
4        count_map[num] = count_map.get(num, 0) + 1
5    result = 0
6    for num, count in count_map.items():
7        if count == 2:
8            result ^= num
9    return result

Complexity note: The time complexity is O(n) because we traverse the array and the HashMap in linear time. The space complexity is O(n) due to the storage of counts in the HashMap.

  • 1Using a HashMap can significantly reduce the time complexity.
  • 2XOR operation is commutative and associative, which allows us to combine results effectively.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.