01
02
03
04
05
06
07
08
09
10
11
A
A2Z Sheet

73. Single Number & The Lone Survivor

Medium
Step 3: Solve Problems on Arrays [Easy -> Medium -> Hard]›Easy

Single Number & The Lone Survivor

MediumFunction: findTheNumberThatAppearsOnceAndOtherNumbersTwice()
ASCI Mission Breakdown • Simple as Hell
"Find the single non-repeated number where every other number appears twice."
Real-World Metaphor:

Think of matching socks. Every pair gets tossed into the laundry basket together. The one odd sock left alone on the table is your answer.

Interactive Visual WalkthroughARRAY-POINTERS
Step 1 / 3
Ballroom: [4, 1, 2, 1, 2]
i
4
[0]
1
[1]
2
[2]
1
[3]
2
[4]
Memory Notepad / State Tracker
XOR Register:4
Evaluating

1. XOR Index 0 (4)

Register = 0 ^ 4 = 4.

How to Think About This (Mental Model)

  1. Initialize result = 0.
  2. XOR every number into result: result ^= num.
  3. All duplicates cancel out to 0.
  4. Return result.

### The Mission Imagine a masquerade ballroom where everyone came in pairs wearing identical masks, except for **one single guest** who came alone! Given an array of integers where every number appears exactly twice except for one number that appears only once, identify the lone survivor. ### The XOR Magic Trick Any number XORed with itself cancels out to zero (`x ^ x = 0`). Any number XORed with zero stays itself (`x ^ 0 = x`). If you XOR every number together across the room, all pairs vaporize into zero, leaving **only the lone guest standing** in **O(N)** time and **O(1)** memory!

Examples

Example 1
Input: nums = [1,2,3,4,5]
Output: 15

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
Topic Tags:
Solve Problems on Arrays [Easy -> Medium -> Hard]EasyfindTheNumberThatAppearsOnceAndOtherNumbersTwice
14px
Ln 1:Col 1
8 lines•150 chars
Spaces: 2•UTF-8
JS(Node v20.12)