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

Naturalists: Sorolla and Zorn

Around 1890, two aspiring painters passed through a phase of Naturalism: in Spain, Joaquín Sorolla, and in Sweden, Anders Zorn, both on their way to become masters.

via The Eclectic Light Company

Moving away from Tailwind, and learning to structure my CSS

Hello! 8 years ago, I wrote excitedly about discovering Tailwind. At that time I really had no idea how to structure my CSS code and given the choice between a pile of complete chaos and Tailwind, I was really happy to choose Tailwind. It helped me make a lot of tiny sites! I spent the last week or ...

via Julia Evans

Add an LLM policy for rust-lang/rust

No comment on this PR may mention the following topics: Long-term social or economic impact of LLMs The environmental impact of LLMs Anything to do with the copyright status of LLM output Moral judgements about people who use LLMs We have asked the moderation team to help us enforce these rules. – A...

via Drew DeVault