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 XOR num
    return result

This runs in O(n)O(n) time and O(1)O(1) space. The XOR operator (boolean logic at the bit level) cancels duplicate pairs, isolating the unique element. XOR turns a hard problem into three lines of code.