Problem 540

Abstract / Summary

Find the unique number in a sorted array where every other number appears exactly twice.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0540.cpp

class Solution {
public:
    int singleNonDuplicate(vector<int>& nums) {
        // XOR trick
        int result = 0;
        for (auto x : nums)
            result ^= x;

        return result;
    }
};
11 lines | 215 bytes | submitted August 7, 2023 | GitHub   11% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 59% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single public method singleNonDuplicate. The method receives a reference to a vector<int> and returns the integer that appears exactly once while all other integers appear twice. The core of the algorithm relies on the bitwise XOR operation, which has the property that a number XORed with itself yields zero and a number XORed with zero yields the number itself. By iteratively applying XOR across the entire array, paired elements cancel each other out, leaving only the unique element.

Key Steps

Initialization of the accumulator

The method begins by declaring an integer variable result and initializing it to zero. This variable serves as the accumulator for the XOR reduction.

int result = 0;

Iteration over the input vector

A range-based for loop traverses each element x in the input vector nums. The loop uses auto to deduce the element type, which simplifies the code and avoids explicit type specifications.

for (auto x : nums)
    result ^= x;

During each iteration, the current element x is combined with the accumulator result using the XOR assignment operator ^=. This operation updates result to the XOR of its previous value and the current element.

Returning the unique element

After the loop completes, the accumulator holds the XOR of all elements in the vector. Because duplicate elements have nullified each other, the remaining value is precisely the element that appears only once. The method returns this value.

return result;

Edge Cases Handled

When the input vector is empty, the loop body never executes, leaving result at its initial value of zero. Consequently, the method returns zero, which is a sensible default for an empty collection. If the vector contains a single element, the loop processes that element once, XORing it with zero and producing the element itself as the result. For vectors where every element appears exactly twice except one, the XOR reduction correctly isolates the solitary element regardless of its position in the array.

Performance Optimizations

The algorithm achieves its goal with a single linear pass over the data, eliminating the need for auxiliary data structures such as hash tables or additional arrays. By using the XOR operation, the method maintains constant auxiliary space, as only the accumulator variable is required. The range-based for loop combined with auto enables the compiler to generate efficient iteration code without the overhead of index management. The use of the XOR assignment operator ^= further streamlines the computation by performing the operation in place. These choices collectively produce a solution that is both time-efficient and memory-light.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of matching socks, but there is one lonely sock that does not have a pair. The goal is to find that special sock hidden in the pile.

The computer does this by starting with a magic box that begins empty. It looks at every sock in the pile one by one. There is a special rule for this magic box. When the box sees a sock, it compares it to what is already inside. If a sock finds its match, they both disappear from the box. If a sock does not have a match, it stays inside.

Because every sock has a partner except for the one lonely sock, all the pairs eventually vanish. The only thing left in the box at the very end is the single sock that could not find a buddy. The computer just peeks inside the box to see what is left, and that is the answer.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.37 | σ = 2.11

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go C TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JS
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
everthis JavaScript
fengvyi C++
fpdjsns C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
YuriSpiridonov Python
zfang399 C++
42 links | 27 authors | 9 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality