↓Skip to main content
  1. LeetCode/

LeetCode 136: Single Number

·1 min· ·
LeetCode Easy Array Bit-Manipulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-16

  • Submissions: Accepted ×3

Approach
#

XOR is commutative and associative with x ^ x = 0 and x ^ 0 = x (Bit Manipulation). XOR all numbers: pairs cancel to 0, leaving the single one, in O(1) extra space.

My Solution
#

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

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Counting with a hash map works but violates the O(1) space requirement.

Interview Explanation
#

XOR is commutative and a number XORed with itself is 0, so XOR-ing everything cancels the pairs and leaves the answer. Time O(n), space O(1).

Related

LeetCode 118: Pascal's Triangle
·1 min
LeetCode Easy Array Dynamic-Programming
LeetCode 118 note: each row starts and ends with 1, and every inner cell is the sum of the two cells above it
LeetCode 108: Convert Sorted Array to Binary Search Tree
·1 min
LeetCode Easy Array Divide-and-Conquer Tree Binary-Search-Tree
LeetCode 108 note: the middle element becomes the root and each half recurses; the halves differ by at most one, so the tree is balanced
LeetCode 119: Pascal's Triangle II
·2 mins
LeetCode Easy Array Dynamic-Programming
LeetCode 119 note: only row rowIndex is needed; update a 1D array from right to left for O(k) space
LeetCode 27: Remove Element
·1 min
LeetCode Easy Array Two-Pointers
LeetCode 27 note: the write pointer copies only values not equal to val, returning how many were written
LeetCode 35: Search Insert Position
·2 mins
LeetCode Easy Array Binary-Search
LeetCode 35 note: find the first position >= target (lower bound); a half-open [l, r) needs r = mid, not r = mid - 1
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9