MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / find_unique_number

Function find_unique_number

bit_manipulation/find_unique_number.py:1–31  ·  view source on GitHub ↗

Given a list of integers where every element appears twice except for one, this function returns the element that appears only once using bitwise XOR. >>> find_unique_number([1, 1, 2, 2, 3]) 3 >>> find_unique_number([4, 5, 4, 6, 6]) 5 >>> find_unique_number([7]) 7

(arr: list[int])

Source from the content-addressed store, hash-verified

1def find_unique_number(arr: list[int]) -> int:
2 """
3 Given a list of integers where every element appears twice except for one,
4 this function returns the element that appears only once using bitwise XOR.
5
6 >>> find_unique_number([1, 1, 2, 2, 3])
7 3
8 >>> find_unique_number([4, 5, 4, 6, 6])
9 5
10 >>> find_unique_number([7])
11 7
12 >>> find_unique_number([10, 20, 10])
13 20
14 >>> find_unique_number([])
15 Traceback (most recent call last):
16 ...
17 ValueError: input list must not be empty
18 >>> find_unique_number([1, 'a', 1])
19 Traceback (most recent call last):
20 ...
21 TypeError: all elements must be integers
22 """
23 if not arr:
24 raise ValueError("input list must not be empty")
25 if not all(isinstance(x, int) for x in arr):
26 raise TypeError("all elements must be integers")
27
28 result = 0
29 for num in arr:
30 result ^= num
31 return result
32
33
34if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected