Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Intuition:
- XOR all grid values with all expected numbers from 1..n^2. Every correct number cancels out,
- so we get xor = missing ^ repeated. Now pick a set bit from xor (mask), which guarantees that
- missing and repeated differ at this bit. Using this mask, split both the grid values and the
- numbers 1..n^2 into two XOR groups; all matching numbers cancel inside their group, leaving
- two candidates (group1, group2) = {missing, repeated}. Finally, check which candidate actually
- exists in the grid: the one present is the repeated value, and the other is the missing value.
- """
- class Solution:
- def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
- xor=0
- k=1
- n=len(grid)
- for i in grid:
- for j in i:
- xor=xor^j^k
- k+=1
- mask=1
- k=1 #xor=10
- while not xor & mask: #for this you can also use: mask = xor & -xor to get the first right most set bit, for eg 100-> 4, it doesn't gives the index but it gives the value
- mask=mask<<1
- group1,group2=0,0
- k=1
- for i in grid:
- for j in i:
- if mask & j:
- group1=group1^j
- else:
- group2=group2^j
- if mask &k:
- group1=group1^k
- else:
- group2=group2^k
- k+=1
- #check which is present from group1 and group 2 in the array for their position in the return array
- check1=False
- for i in grid:
- if group1 in i:
- check1=True
- if check1:
- return [group1,group2]
- else:
- return [group2,group1]
- return [group1,group2]
Advertisement
Add Comment
Please, Sign In to add comment