Problem 260

Abstract / Summary

Find the two numbers in an array that appear once while all others appear twice without using extra space.

Note

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

Python 0260.py

class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
        all = 0
        for n in nums:
            all ^= n

        # x^x = 0
        # "all" is result1 ^ result2
        # the lowest set bit in "all" is the first difference between result1 and result2

        # partition all numbers based on that bit
        # there will be two groups with one unique number each
        # repeat the XOR trick to get that number

        mask = 1
        while (all & mask) == 0:
            mask <<= 1

        a = b = 0
        for n in nums:
            if n & mask:
                a ^= n
            else:
                b ^= n

        return a, b
26 lines | 696 bytes | submitted September 4, 2023 | GitHub   40% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (800k+ 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 implementation solves the classic “single number III” problem: given an integer array where every element appears exactly twice except for two distinct numbers, it returns those two unique values. The algorithm relies on the properties of the XOR operation to isolate the two outliers without auxiliary data structures.

Step 1 - Compute the XOR of the entire collection

The first loop iterates through the input list and accumulates the XOR of every element into a variable named all. Because XOR cancels identical values (x ^ x = 0), the resulting value is the XOR of the two unique numbers only.

all = 0
for n in nums:
    all ^= n

At this point all equals result1 ^ result2. The bits that are set in all indicate positions where the two unique numbers differ.

Step 2 - Identify a distinguishing bit mask

To separate the two unique numbers, the algorithm needs a bit that is set in exactly one of them. It finds the least-significant set bit of all by left-shifting a mask until the bitwise AND with all becomes non-zero.

mask = 1
while (all & mask) == 0:
    mask <<= 1

The chosen mask isolates the first position where the two unique numbers diverge, guaranteeing that one of the numbers will have this bit set while the other will not.

Step 3 - Partition the array and recover each unique value

With the distinguishing mask, the algorithm performs a second pass over the array. It groups numbers based on whether the mask bit is set, applying XOR within each group. Because duplicate numbers fall into the same group, they cancel out, leaving only the unique member of that group.

a = b = 0
for n in nums:
    if n & mask:
        a ^= n
    else:
        b ^= n

After the loop, a and b hold the two numbers that appear only once. The function returns them as a tuple.

Edge Cases Handled

The code naturally accommodates negative integers because the XOR operation works uniformly on two’s-complement representations. When the input contains the minimum or maximum 32-bit values, the bitwise logic still functions correctly, as the mask search examines each bit position independently of the numeric magnitude.

If the two unique numbers differ only in higher-order bits, the while-loop will shift the mask until it reaches the appropriate position, ensuring that the partitioning step still separates them correctly. The algorithm also tolerates arrays where the duplicate elements are interleaved with the unique ones; the grouping relies solely on the mask bit, not on element order.

Performance Optimizations

The solution processes the input list twice, each pass performing only simple arithmetic and bitwise operations. This minimal traversal reduces cache pressure and keeps the runtime low even for large inputs. All auxiliary variables (all, mask, a, b) are scalar integers, so the memory footprint stays constant regardless of input size. The mask discovery loop stops as soon as the first differing bit is found, avoiding unnecessary work. By leveraging XOR’s cancellation property, the algorithm eliminates the need for hash tables or sorting, which would introduce additional overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine holding a big pile of toys where almost every toy has an exact twin, but there are two special toys hiding in the pile that do not have any friends. The goal is to find those two special lonely toys.

First, the code uses a neat math trick by mixing all the toy numbers together. When two identical toys meet, the math makes them vanish. After mixing everyone, only the two lonely toys are left blended together.

Next, the code looks for a tiny clue to tell the two lonely toys apart. It zooms in on a specific spot in their numbers where they are different. It uses a mask, which is like a tiny flashlight, to peek at that specific spot for every single toy in the pile.

Finally, the code splits all the toys into two crates. One crate gets all the toys that have a light on in that spot, and the other crate gets the toys that have the light off. By mixing the toys in each crate separately using the same trick as before, the friends disappear and only the two lonely toys remain, one standing proud in each crate.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.85 | σ = 1.63

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 Rust Python JS C# Go TS
LeetcodeHelp C++ Java Python
MemoryLimitExceeded C++ Python
Progiez C++ Java Python
github aylei Rust
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fpdjsns C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fpdjsns C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
47 links | 30 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Single Number iii | LeetCode 260 | C++, Java, Python3'
Knowledge Center 14 mins
Single Number iii | LeetCode 260 | C++, Java, Python3
YouTube video 'Single Number III | Detailed Explanation | Leetcode 260 | codestorywithMIK'
codestorywithMIK 26 mins
Single Number III | Detailed Explanation | Leetcode 260 | codestorywithMIK
YouTube video '260. Single Number III | XOR Properties | Masking Technique | Retrieve Last Set Bit of a Number'
Aryan Mittal 20 mins
260. Single Number III | XOR Properties | Masking Technique | Retrieve Last Set Bit of a Number
YouTube video 'single number iii | single number 3 | single number 3 leetcode | leetcode 260 | bitwise xor'
Naresh Gupta 15 mins
single number iii | single number 3 | single number 3 leetcode | leetcode 260 | bitwise xor
YouTube video 'Single Number III | Leetcode 260 | Live coding session 🔥🔥🔥'
Coding Decoded 9 mins
Single Number III | Leetcode 260 | Live coding session 🔥🔥🔥
YouTube video 'Single Number III | Day 23 | O(N) O(1) | HashSet [ July LeetCoding Challenge ] [ Leetcode #260 ]'
Algorithms Made Easy 6 mins
Single Number III | Day 23 | O(N) O(1) | HashSet [ July LeetCoding Challenge ] [ Leetcode #260 ]
YouTube video 'Daily Leetcode #1522: May 31, 2024 - 260. Single Number III'
Programming Live with Larry 18 mins
Daily Leetcode #1522: May 31, 2024 - 260. Single Number III
YouTube video '260. Single Number III (Updated Video in description) (Leetcode Medium)'
Programming Live with Larry 26 mins
260. Single Number III (Updated Video in description) (Leetcode Medium)
YouTube video 'Single Number III   (LeetCode 260)  (Hashmap, Bit Manipulation)'
CodeWithARB 44 mins
Single Number III (LeetCode 260) (Hashmap, Bit Manipulation)
YouTube video 'Single Number III | Leet code 260 | Theory explained + Python code | July Leet code challenge'
Sai Anish Malla 3 mins
Single Number III | Leet code 260 | Theory explained + Python code | July Leet code challenge
YouTube video 'Daily Leetcode #114: Jul 23, 2020 - 260. Single Number III'
Programming Live with Larry 8 mins
Daily Leetcode #114: Jul 23, 2020 - 260. Single Number III
YouTube video '260. Single Number III | May | Java | C++'
Mayur Programming Club 19 mins
260. Single Number III | May | Java | C++
YouTube video 'Daily Leetcode #585: Nov 06, 2021 - 260. Single Number III'
Programming Live with Larry 18 mins
Daily Leetcode #585: Nov 06, 2021 - 260. Single Number III
YouTube video 'Single Number III | LeetCode 260 | Coders Camp'
Coders Camp 16 mins
Single Number III | LeetCode 260 | Coders Camp
YouTube video 'Single Number III || November LeetCoding Challenge || Bit Manipulation'
TechWithSaumya 13 mins
Single Number III || November LeetCoding Challenge || Bit Manipulation
YouTube video 'LEETCODE PROBLEM 260 : Single Number III (MEDIUM) || EASY APPROACH FULLY EXPLAINED C++(CPP) || 🔥 🔥||'
Gurnoor Chhabra [NIT-JALANDHAR] 17 mins
LEETCODE PROBLEM 260 : Single Number III (MEDIUM) || EASY APPROACH FULLY EXPLAINED C++(CPP) || 🔥 🔥||
YouTube video 'LeetCode 260 - Single Number III - Java'
Alpha-Code 16 mins
LeetCode 260 - Single Number III - Java
YouTube video '30. LeetCode 260. Single Number III [ JAVASCRIPT ]'
Web Fusion with Bharadwaj 4 mins
30. LeetCode 260. Single Number III [ JAVASCRIPT ]
YouTube video 'Day 315: LeetCode Problem 260. Single Number III - Swift'
iOSxBank 10 mins
Day 315: LeetCode Problem 260. Single Number III - Swift
YouTube video 'Single Number III | LeetCode  260 | 2 Approaches | Bits | |Java Solution | Developer Coder'
Developer Coder 18 mins
Single Number III | LeetCode 260 | 2 Approaches | Bits | |Java Solution | Developer Coder
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

25 solutions   September 4, 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