Single Number – Solution & Complexity
Solution Walkthrough
Step 1: Understand the Pattern
- Every value appears exactly twice except one value.
- We need to return the value that appears once.
- The challenge asks for linear time and no extra memory.
Step 2: Counting Approach
- A dictionary can count how many times each number appears.
- Then we return the number with count
1. - This is O(n) time, but it uses O(n) extra space.
Step 3: Key Insight: XOR Cancels Pairs
- XOR has useful properties:
x ^ x = 0andx ^ 0 = x. - XOR is also commutative, so order does not matter.
- When all numbers are XORed together, paired values cancel and only the single value remains.
- XOR has useful properties:
Step 4: Accumulate with XOR
- Start with
result = 0. - XOR every number into
result. - After the loop,
resultis the number that appeared once.
- Start with
Step 5: Final Solution and Complexity
- The XOR solution meets the follow-up requirement.
- Time complexity is O(n).
- Space complexity is O(1).