Single Number

Problem

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

You must implement a solution with a linear runtime complexity and use only constant extra space.

Example 1:

Input: nums = [2,2,1]
Output: 1
Example 2:

Input: nums = [4,1,2,1,2]
Output: 4
Example 3:

Input: nums = [1]
Output: 1

Constraints:

  • 1 <= nums.length <= 3 * 10^4
  • -3 10^4 <= nums[i] <= 3 10^4
  • Each element in the array appears twice except for one element which appears only once.

Solution

Relies on that xor trick. Related.

class Solution {
    public int singleNumber(int[] nums) {
        var counter = 0;
        for (var n : nums) {
            counter ^= n;
        }
        return counter;
    }
}

Recent posts from blogs that I like

The Great Ladies of Impressionism

Brief reviews of the paintings of 3 of the Great Ladies of Impressionism, Berthe Morisot, Marie Bracquemond, and Eva Gonzalès.

via The Eclectic Light Company

Claude Fable is relentlessly proactive

via Simon Willison

Who Runs the Ransomware Group ‘The Gentlemen?’

A cybercrime group known as The Gentlemen has emerged as the second most active ransomware gang by victim count, rapidly attracting a talented pool of hackers through an aggressive recruitment strategy that promises affiliates 90 percent of any ransom paid by victims. This post examines clues pointi...

via Krebs on Security