Skip to content

Add find_unique_number algorithm to bit manipulation #12654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions bit_manipulation/find_unique_number.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
def find_unique_number(arr: list[int]) -> int:
"""
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
>>> find_unique_number([10, 20, 10])
20
>>> find_unique_number([])
Traceback (most recent call last):
...
ValueError: input list must not be empty
>>> find_unique_number([1, 'a', 1])
Traceback (most recent call last):
...
TypeError: all elements must be integers
"""
if not arr:
raise ValueError("input list must not be empty")
if not all(isinstance(x, int) for x in arr):
raise TypeError("all elements must be integers")

result = 0
for num in arr:
result ^= num
return result


if __name__ == "__main__":
import doctest

doctest.testmod()