Problem 136

Abstract / Summary

Find the element that appears only once in an array where every other element appears exactly twice.

Note

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

C++ 0136.cpp

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

        return result;
    }
};
10 lines | 187 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (6+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
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 method that extracts the unique integer from a collection where every other integer appears exactly twice. It leverages the exclusive-or (XOR) operation to cancel out paired values, leaving the solitary element as the final result.

Key Steps

Initialization

int result = 0;

A variable is prepared to accumulate the XOR of all elements. Starting with zero ensures that the first XOR operation yields the first element unchanged, establishing a neutral base for subsequent cancellations.

Iteration and XOR Accumulation

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

The loop traverses the entire input vector, applying XOR between the accumulator and each element. Because XOR of a number with itself yields zero and XOR with zero yields the number, paired values neutralize each other while the unpaired value persists.

Return of the Unique Value

return result;

After the loop completes, the accumulator holds the solitary integer, which is then returned to the caller.

Edge Cases Handled

When the input vector is empty, the loop body never executes, and the method returns the initial zero value, providing a defined outcome for this boundary condition. The XOR operation works uniformly across the full range of signed 32-bit integers, so negative numbers are processed correctly without additional handling. The algorithm also accommodates vectors of any length that satisfy the “all but one appear twice” contract, regardless of the position of the unique element.

Performance Optimizations

The solution achieves its goal with a single pass over the data, avoiding auxiliary containers such as hash tables or frequency maps. By relying solely on a primitive integer variable for state, it maintains a constant memory footprint. The use of the XOR operator, which is a low-level CPU instruction, ensures that each iteration incurs minimal computational overhead, delivering efficient execution even for large input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of toy blocks where every block has a twin that looks exactly the same, except for one very special block that has no twin at all. The goal is to find that lonely block.

To do this, the computer starts with an empty box called result. It picks up every block one by one and uses a magic trick with a math tool called an exclusive or. When the computer uses this tool, two identical blocks cancel each other out and disappear from the box. Because almost every block has a twin, all the pairs eventually vanish. The only thing left sitting in the box at the very end is the special block that had no partner to cancel it out. This acts like a secret way to highlight the unique item by letting all the other pieces hide each other.

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 = 9 | μ = 9.19 | σ = 0.67

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ C Python Java C# Rust JS TS Go Swift
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++ TS
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, Python, Rust, Swift, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
fengvyi C++
gaosq0604 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++, TypeScript
MacJim C++
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
62 links | 42 authors | 13 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Single Number - Leetcode 136 - Bit Manipulation (Python)'
Greg Hogg 4 mins
Single Number - Leetcode 136 - Bit Manipulation (Python)
YouTube video 'Single Number | Leetcode 136 | XOR | Sorting | Hashmap'
Ayushi Sharma 13 mins
Single Number | Leetcode 136 | XOR | Sorting | Hashmap
YouTube video 'Leetcode | 136. Single Number | Easy | Java Solution [2 Solutions]'
Developer Docs 7 mins
Leetcode | 136. Single Number | Easy | Java Solution [2 Solutions]
YouTube video 'LeetCode 136: Single Number [Python]'
Frederik Müller 12 mins
LeetCode 136: Single Number [Python]
YouTube video 'LeetCode 136: Single Number - Interview Prep Ep 35'
Fisher Coder 16 mins
LeetCode 136: Single Number - Interview Prep Ep 35
YouTube video '8. Single Number | Arrays - Easy | Learn DSA | Leetcode 136'
Ayushi Sharma 5 mins
8. Single Number | Arrays - Easy | Learn DSA | Leetcode 136
YouTube video 'Single Number - LeetCode 136 | Find the element that appears once'
Java2Novice 5 mins
Single Number - LeetCode 136 | Find the element that appears once
YouTube video 'Single Number - LeetCode 136 - Python #leetcode'
Deepti Talesra 7 mins
Single Number - LeetCode 136 - Python #leetcode
YouTube video 'Single Number - LeetCode 136 - Java | XOR Crash Course'
LeetCode University 11 mins
Single Number - LeetCode 136 - Java | XOR Crash Course
YouTube video 'Single Number - LeetCode 136 - Blind 75 - Bit Manipulation'
One Code Man 7 mins
Single Number - LeetCode 136 - Blind 75 - Bit Manipulation
YouTube video 'LeetCode 136: Single Number | C# Solution | XOR Bit Manipulation |'
Code Scribbler 11 mins
LeetCode 136: Single Number | C# Solution | XOR Bit Manipulation |
YouTube video 'Solving LeetCode problem 136 in APL (Single Number)'
Rodrigo's APL Corner 10 mins
Solving LeetCode problem 136 in APL (Single Number)
YouTube video 'Single Number | Leetcode 136 | Live coding session 🔥🔥🔥 | XOR'
Coding Decoded 3 mins
Single Number | Leetcode 136 | Live coding session 🔥🔥🔥 | XOR
YouTube video 'Single Number - Leetcode 136 | Efficient XOR Solution in JavaScript'
Web Coder Abhishek 4 mins
Single Number - Leetcode 136 | Efficient XOR Solution in JavaScript
YouTube video '136. Single Number || leetcode || code explanation || top 100 questions'
code Explainer 3 mins
136. Single Number || leetcode || code explanation || top 100 questions
YouTube video 'Leetcode 136 Single Number (Java) - O(1) Space 100%'
TheAnalyticGuy 3 mins
Leetcode 136 Single Number (Java) - O(1) Space 100%
YouTube video 'Daily Leetcode #686: Feb 15, 2022 - 136. Single Number'
Programming Live with Larry 4 mins
Daily Leetcode #686: Feb 15, 2022 - 136. Single Number
YouTube video 'Single Number - LeetCode #136 - C++'
Sean Chuah 5 mins
Single Number - LeetCode #136 - C++
YouTube video 'LeetCode 136 | Single Number | Solution Explained (Java + Whiteboard)'
Xavier Elon 11 mins
LeetCode 136 | Single Number | Solution Explained (Java + Whiteboard)
YouTube video 'Leetcode 136. Single Number (Python)'
Math Geeks 3 mins
Leetcode 136. Single Number (Python)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 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