Skip to content
LEETFLIX

Easy · XOR fold. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 136. Single Number. The copyrighted prompt is on LeetCode. This page is a working XOR fold for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[4, 1, 2, 1, 2]

Output

4

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

XOR everything

x ^ x = 0 and x ^ 0 = x, so pairs cancel and the lonely value remains.

XOR is associative and commutative. Every duplicate pair vanishes; the unique number is what is left.

Algorithm

  1. Start acc = 0.
  2. XOR each value into acc.
  3. Return acc.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def singleNumber(self, nums: list[int]) -> int:        acc = 0        for x in nums:            acc ^= x        return acc
Watch this run

03

Interactive walkthrough

Playing “XOR everything”. Edit the input, hit Run, then scrub.

Approach: XOR everything

Loading animation…