classUnion:def__init__(self,n): self.roots =list(range(n))deffind(self,i):if self.roots[i]== i:return i self.roots[i]= self.find(self.roots[i])return self.roots[i]defunion(self,a,b): self.roots[self.find(a)]= self.find(b)defconnected(self,a,b):return self.find(a)== self.find(b)classSolution:defminSwapsCouples(self,row: List[int]) ->int: n =len(row) union =Union(n //2)for i inrange(n //2): left, right = i *2, i *2+1 lidx, ridx = row[left]//2, row[right]//2if lidx != ridx: union.union(lidx, ridx) count, seen =0,set()for i inrange(n //2): index = union.find(i)if index notin seen: seen.add(index) count +=1return n //2- count