Skip to content

Single Number Algorithm Added #12041

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

Closed
wants to merge 1 commit into from
Closed
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
30 changes: 30 additions & 0 deletions bit_manipulation/single_num.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def single_number(nums: list[int]) -> int:
"""
Find the single number in an array where every other number appears twice.

Args:
nums: List of integers where every integer appears twice except for one.

Returns:
The single integer that appears once.

Example:
>>> single_number([4, 1, 2, 1, 2])
4
>>> single_number([2, 2, 1])
1
>>> single_number([1])
1
"""
result = 0
for num in nums:
result ^= num # Applying XOR operation
return result


if __name__ == "__main__":
# Test cases
print(single_number([4, 1, 2, 1, 2])) # Output: 4
print(single_number([2, 2, 1])) # Output: 1
print(single_number([1])) # Output: 1
print(single_number([5, 3, 5, 7, 3])) # Output: 7