Find the Two Numbers Appearing Odd Number of Times
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
2 ≤ nums.length ≤ 3 × 10⁴ - ◆
-3 × 10⁴ ≤ nums[i] ≤ 3 × 10⁴ - ◆
Exactly two distinct values in nums occur an odd number of times; every other value occurs an even number of times
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Hashmap Counting
GoodCount how many times every value shows up, using a running tally. Once every value has been tallied, scan the tallies for the two whose count didn't land on an even number — those are the two odd ones out. Sort the pair so the smaller value comes first.
O(n)O(n)1class Solution {
2 public int[] findOddOccurringPair(int[] nums) {
3 Map<Integer, Integer> counts = new HashMap<>();
4 for (int num : nums) {
5 counts.put(num, counts.getOrDefault(num, 0) + 1);
6 }
7 List<Integer> oddOnes = new ArrayList<>();
8 for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
9 if (entry.getValue() % 2 != 0) {
10 oddOnes.add(entry.getKey());
11 }
12 }
13 Collections.sort(oddOnes);
14 return new int[]{oddOnes.get(0), oddOnes.get(1)};
15 }
16}Optimal — XOR Split by Differing Bit
OptimalA running XOR across the whole array collapses every even-count value to nothing, regardless of how many times it actually repeats, leaving behind the XOR of just the two odd-count values combined. Isolate one bit where those two values must disagree, then split every number into two groups by whether that bit is set — XOR-ing within each group isolates one of the pair per group, since whatever else shares that group still cancels however many times it repeats.
O(n)O(1) extra1class Solution {
2 public int[] findOddOccurringPair(int[] nums) {
3 int xorAll = 0;
4 for (int num : nums) {
5 xorAll ^= num;
6 }
7 int diffBit = xorAll & (-xorAll);
8 int a = 0, b = 0;
9 for (int num : nums) {
10 if ((num & diffBit) != 0) {
11 a ^= num;
12 } else {
13 b ^= num;
14 }
15 }
16 return a < b ? new int[]{a, b} : new int[]{b, a};
17 }
18}