Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

single-number.py

bit-manipulation/single-number.py · Python · 998 B · 2026-01-31 14:33

Back to folder
# Brute force or using a hash map or sorting or bit manipulation (xor)
# bit 

# Brute force: O(n^2) time, O(1) space
def singleNumber(nums: list[int]) -> int:
    for i in range(len(nums)):
        flag = True
        for j in range(len(nums)):
            if i != j and nums[i] == nums[j]:
                flag = False
                break
        if flag:
            return nums[i]

# Hash map: O(n) time, O(n) space
def singleNumber(nums: list[int]) -> int:
    freq = {}
    for n in nums:
        freq[n] = freq.get(n, 0) +1

    for n in freq.keys():
        if freq[n] < 2:
            return n

    return -1

# Sorting: O(n lg n) time, O(1) space
def singleNumber(nums: list[int]) -> int:
    nums.sort()
    i = 0
    while i < len(nums) -1:
        if nums[i] != nums[i+1]:
            return nums[i]
        i += 2
    return nums[-1]

# Bit manipulation: O(n) time, O(1) space
def singleNumber(nums: list[int]) -> int:
    res = 0
    for n in nums:
        res ^= n
    return res