Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import heapq
- class Solution:
- def minSwaps(self, nums: List[int], forbidden: List[int]) -> int:
- n = len(nums)
- mapp = defaultdict(lambda:defaultdict(lambda:0))
- sameCount = {}
- for i in range(n):
- numm = nums[i]
- forb = forbidden[i]
- mapp[forb][numm] += 1
- if forb not in sameCount:
- sameCount[forb] = 0
- if forb == numm:
- sameCount[forb]+= 1
- #lets start collision effect,higher sameCount are the issue for us
- ordd = []
- for k,v in sameCount.items():
- heapq.heappush(ordd,[-v,k])
- #trying to breaking all the bad bonds with
- swaps = 0
- exitt = 0
- while len(ordd)>=2:
- bigger = heapq.heappop(ordd)
- smaller = heapq.heappop(ordd)
- #reverting to original val
- bigger[0] = -bigger[0]
- smaller[0] = -smaller[0]
- subtractor = smaller[0]
- remaining = bigger[0]-smaller[0]
- mapp[smaller[1]][smaller[1]] -= subtractor
- mapp[smaller[1]][bigger[1]] += subtractor
- mapp[bigger[1]][bigger[1]] -= subtractor
- mapp[bigger[1]][smaller[1]] += subtractor
- swaps += subtractor
- if remaining>0:
- heapq.heappush(ordd,[-remaining,bigger[1]])
- remain = 0
- #if still ordd present means there is still one guy having bad bonds
- #he needs to be cleanesed meticulously without touching its current nums position or
- #without touching its forbidden position
- if len(ordd):
- rem,target = heapq.heappop(ordd)
- rem = -rem
- remain = rem
- for k,mapi in mapp.items():
- if target==k:
- continue
- for kk,count in mapi.items():
- if target==kk:
- continue
- else:
- mini = min(count,rem)
- rem -= mini
- remain = rem
- swaps += mini
- if rem<=0:
- exitt = 1
- break
- if exitt == 1:
- break
- if remain>0:
- return -1
- else:
- return swaps
Advertisement
Add Comment
Please, Sign In to add comment