Math Fundamentals18 sections · 814 units
Open in Course

Single Number - Implementation

The code

Here's the complete solution:


function singleNumber(nums)
    result := 0
    for each num in nums
        result := result ^ num
    return result

Initialize result to 0 (the XOR identity). XOR every number in the array. Pairs cancel out, leaving only the unique number. Time: O(n)O(n). Space: O(1)O(1). No hash map, no sorting, just one pass with XOR.