Skip to content
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
44 changes: 44 additions & 0 deletions bit_manipulation/find_number_that_appears_only_once_in_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
'''
This problem comes from LeetCode 136: Single Number

Problem Statement: You are given an list of number where each number appears twice in the list but there is a single number that appears once only. Find that single number.

Check failure on line 4 in bit_manipulation/find_number_that_appears_only_once_in_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

bit_manipulation/find_number_that_appears_only_once_in_array.py:4:89: E501 Line too long (172 > 88)

Intuition:
- Hence we know that a ^ a = 0 (^ is XOR binary operator)
- We can XOR all numbers, then we will get the only single number
- Example: let's take nums = [1, 2, 4, 1, 4, 3, 2]
- We can see all numbers appears twice except 3
- If we take XOR of all element, we will get 3, let me demonstrate -
- 1 ^ 2 ^ 4 ^ 1 ^ 4 ^ 3 ^ 2
- Since we know a ^ a = 0, we can cancel them out -
- 1 ^ 1 ^ 2 ^ 2 ^ 4 ^ 4 ^ 3
- 0 ^ 0 ^ 0 ^ 3
- We also know a ^ 0 = a, then we will get our answer as 3

Complexities:
- Time: O(n)
- Space: O(1)
'''

def find_single_number(nums):
'''
LeetCode 136: Single Number
https://leetcode.com/problems/single-number/description/

>>> find_single_number([1, 4, 1, 7, 9, 2, 9, 7, 2])
4
>>> find_single_number([1, 2, 4, 1, 4, 3, 2])
3
>>> find_single_number([4, 1, 2, 1, 2])
4
'''
single_num = 0

Check failure on line 36 in bit_manipulation/find_number_that_appears_only_once_in_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

bit_manipulation/find_number_that_appears_only_once_in_array.py:36:1: W293 Blank line contains whitespace
for i in nums:
single_num = single_num ^ i;

Check failure on line 38 in bit_manipulation/find_number_that_appears_only_once_in_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E703)

bit_manipulation/find_number_that_appears_only_once_in_array.py:38:36: E703 Statement ends with an unnecessary semicolon

Check failure on line 39 in bit_manipulation/find_number_that_appears_only_once_in_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

bit_manipulation/find_number_that_appears_only_once_in_array.py:39:1: W293 Blank line contains whitespace
return single_num

if __name__ == "__main__":
import doctest
doctest.testmod()
Loading