Bit Others¶
Table of Contents¶
- 136. Single Number (Easy)
- 287. Find the Duplicate Number (Medium)
- 260. Single Number III (Medium)
- 2965. Find Missing and Repeated Values (Easy)
- 137. Single Number II (Medium)
- 645. Set Mismatch (Easy)
- 190. Reverse Bits (Easy)
- 371. Sum of Two Integers (Medium)
- 201. Bitwise AND of Numbers Range (Medium)
- 2154. Keep Multiplying Found Values by Two (Easy)
- 2044. Count Number of Maximum Bitwise-OR Subsets (Medium)
- 2438. Range Product Queries of Powers (Medium)
- 1680. Concatenation of Consecutive Binary Numbers (Medium)
- 1261. Find Elements in a Contaminated Binary Tree (Medium)
- 89. Gray Code (Medium)
- 1238. Circular Permutation in Binary Representation (Medium)
- 982. Triples with Bitwise AND Equal To Zero (Hard)
- 3307. Find the K-th Character in String Game II (Hard)
- 1611. Minimum One Bit Operations to Make Integers Zero (Hard)
- 751. IP to CIDR (Medium) 👑
- 3141. Maximum Hamming Distances (Hard) 👑
136. Single Number¶
from functools import reduce
from operator import xor
from typing import List
# XOR
def singleNumber(nums: List[int]) -> int:
res = 0
for num in nums:
res ^= num
return res
# XOR
def singleNumberXOR(nums: List[int]) -> int:
return reduce(xor, nums)
# XOR
def singleNumberXORLambda(nums: List[int]) -> int:
return reduce(lambda x, y: x ^ y, nums)
nums = [4, 1, 2, 1, 2]
print(singleNumber(nums)) # 4
print(singleNumberXOR(nums)) # 4
print(singleNumberXORLambda(nums)) # 4
287. Find the Duplicate Number¶
"""
- Find the duplicate number in an array containing `n + 1` integers where each integer is between `1` and `n` inclusive.
- Floyd's Tortoise and Hare (Cycle Detection)
- 141. Linked List Cycle
- 142. Linked List Cycle II
- Time Complexity: O(n)
- Space Complexity: O(1)
Example: `nums = [1, 3, 4, 2, 2]`
| 0 | 1 | 2 | 3 | 4 |
| :--: | :--: | :--: | :--: | :--: |
| 1 | 3 | 4 | 2 | 2 |
"""
from typing import List
# Floyd Cycle Detection Algorithm
def findDuplicate(nums: List[int]) -> int:
fast, slow = nums[0], nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
nums = [1, 3, 4, 2, 2]
print(findDuplicate(nums)) # 2
260. Single Number III¶
2965. Find Missing and Repeated Values¶
137. Single Number II¶
645. Set Mismatch¶
190. Reverse Bits¶
371. Sum of Two Integers¶
201. Bitwise AND of Numbers Range¶
2154. Keep Multiplying Found Values by Two¶
2044. Count Number of Maximum Bitwise-OR Subsets¶
2438. Range Product Queries of Powers¶
1680. Concatenation of Consecutive Binary Numbers¶
1261. Find Elements in a Contaminated Binary Tree¶
-
Tags: Hash Table, Tree, Depth First Search, Breadth First Search, Design, Binary Tree