imashutosh51

Find Missing and Repeated Values

Feb 4th, 2026
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. """
  2. Intuition:
  3. XOR all grid values with all expected numbers from 1..n^2. Every correct number cancels out,
  4. so we get xor = missing ^ repeated. Now pick a set bit from xor (mask), which guarantees that
  5. missing and repeated differ at this bit. Using this mask, split both the grid values and the
  6. numbers 1..n^2 into two XOR groups; all matching numbers cancel inside their group, leaving
  7. two candidates (group1, group2) = {missing, repeated}. Finally, check which candidate actually
  8. exists in the grid: the one present is the repeated value, and the other is the missing value.
  9. """
  10.  
  11. class Solution:
  12.     def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
  13.         xor=0
  14.         k=1
  15.         n=len(grid)
  16.         for i in grid:
  17.             for j in i:
  18.                 xor=xor^j^k
  19.                 k+=1
  20.         mask=1
  21.         k=1 #xor=10
  22.  
  23.         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
  24.             mask=mask<<1
  25.         group1,group2=0,0
  26.         k=1
  27.         for i in grid:
  28.             for j in i:
  29.                 if mask & j:
  30.                     group1=group1^j
  31.                 else:
  32.                     group2=group2^j
  33.                 if mask &k:
  34.                     group1=group1^k
  35.                 else:
  36.                     group2=group2^k
  37.                 k+=1
  38.        
  39.         #check which is present from group1 and group 2 in the array for their position in the return array
  40.         check1=False
  41.         for i in grid:
  42.             if group1 in i:
  43.                 check1=True
  44.  
  45.         if check1:
  46.             return [group1,group2]
  47.         else:
  48.             return [group2,group1]
  49.        
  50.         return [group1,group2]
  51.  
Advertisement
Add Comment
Please, Sign In to add comment