Skip to content

Conversation

yanglbme
Copy link
Member

No description provided.

@idoocs idoocs added core team Issues or pull requests from core team cpp Issues or Pull requests relate to .cpp code go Issues or Pull requests relate to .go code java Issues or Pull requests relate to .java code md Issues or Pull requests relate to .md files py Issues or Pull requests relate to .py code ts Issues or Pull requests relate to .ts code labels Oct 14, 2025
@yanglbme yanglbme merged commit cf8d64c into main Oct 14, 2025
14 checks passed
@yanglbme yanglbme deleted the dev branch October 14, 2025 23:44
Copy link

@giruuuuj giruuuuj left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Problem Understanding
The problem is to find two numbers that appear twice in an array containing numbers from 0 to n-1, where the array length is n+2.

Bit Manipulation Solution Analysis
Core Logic
python
class Solution:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
n = len(nums) - 2
xx = nums[n] ^ nums[n + 1]
for i in range(n):
xx ^= i ^ nums[i]
k = xx.bit_length() - 1
ans = [0, 0]
for x in nums:
ans[x >> k & 1] ^= x
for i in range(n):
ans[i >> k & 1] ^= i
return ans
Step-by-Step Explanation
Initial XOR Setup

python
n = len(nums) - 2
xx = nums[n] ^ nums[n + 1]
Calculate n as the expected range (0 to n-1)

Start XOR with the last two elements

Compute Total XOR

python
for i in range(n):
xx ^= i ^ nums[i]
XOR all numbers from 0 to n-1 with corresponding array elements

The result xx contains the XOR of the two duplicate numbers

Find Differentiating Bit

python
k = xx.bit_length() - 1
Find the highest set bit where the two duplicates differ

Separate and Find Duplicates

python
ans = [0, 0]
for x in nums:
ans[x >> k & 1] ^= x
for i in range(n):
ans[i >> k & 1] ^= i
return ans
Group numbers based on the k-th bit

XOR operations cancel out non-duplicate numbers

Final result contains the two duplicates

Time & Space Complexity
Time Complexity: O(n) - Single pass through the array

Space Complexity: O(1) - Constant extra space

Key Insight
The solution cleverly uses XOR properties:

a ^ a = 0

a ^ 0 = a

XOR is commutative and associative

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core team Issues or pull requests from core team cpp Issues or Pull requests relate to .cpp code go Issues or Pull requests relate to .go code java Issues or Pull requests relate to .java code md Issues or Pull requests relate to .md files py Issues or Pull requests relate to .py code ts Issues or Pull requests relate to .ts code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants