Lesson 241 of 250
136. Single Number
NeetCode: Single Number · LeetCode: 136. Single Number · Difficulty: Easy
Every element of nums appears exactly twice, except one that appears once. Return that single element, in linear time and constant extra space.
Example
Input: nums = [2, 2, 1] Output: 1
Input: nums = [4, 1, 2, 1, 2] Output: 4Brute force: count occurrences
Count each value in a HashMap<Integer, Integer> with merge, then return the key whose count is 1. Only one key has that count, so the unspecified HashMap iteration order does not affect the result. e.getValue() == 1 compares an Integer with an int, which unboxes the value, so it is a value comparison. It is linear time but needs a map as large as the number of distinct values.
import java.util.HashMap;
import java.util.Map;
public class Main {
static class Solution {
public int singleNumber(int[] nums) {
Map<Integer, Integer> counts = new HashMap<>();
for (int x : nums) {
counts.merge(x, 1, Integer::sum);
}
for (Map.Entry<Integer, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) {
return e.getKey();
}
}
return 0;
}
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.singleNumber(new int[]{2, 2, 1}));
System.out.println(s.singleNumber(new int[]{4, 1, 2, 1, 2}));
System.out.println(s.singleNumber(new int[]{-7}));
}
}1
4
-7Time: O(n). Space: O(n).
Optimal: XOR everything
XOR has three properties: a ^ a = 0, a ^ 0 = a, and it is commutative and associative. XOR all numbers together and the paired values cancel each other in whatever order they appear, leaving only the value that appears once.
Example 4 ^ 1 ^ 2 ^ 1 ^ 2: reorder to (1 ^ 1) ^ (2 ^ 2) ^ 4 = 0 ^ 0 ^ 4 = 4.
public class Main {
static class Solution {
public int singleNumber(int[] nums) {
int acc = 0;
for (int x : nums) {
acc ^= x;
}
return acc;
}
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.singleNumber(new int[]{2, 2, 1}));
System.out.println(s.singleNumber(new int[]{4, 1, 2, 1, 2}));
System.out.println(s.singleNumber(new int[]{-7}));
}
}1
4
-7Time: O(n). Space: O(1).
