#136

Single Number

Easy
ArrayBit ManipulationBit ManipulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using the XOR operator is efficient because it has properties that allow us to cancel out duplicate numbers. This way, we can find the unique number in linear time with constant space.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable result to 0.
  2. 2Step 2: Loop through each number in the array and apply the XOR operation with result.
  3. 3Step 3: The final value of result will be the unique number.
solution.py5 lines
1def singleNumber(nums):
2    result = 0
3    for num in nums:
4        result ^= num
5    return result

Complexity note: The time complexity is O(n) because we traverse the array once, and the space complexity is O(1) since we only use a single variable to store the result.

  • 1XOR operation allows us to cancel out duplicate numbers efficiently.
  • 2The unique number will remain after all duplicates are canceled out.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.