Kali_prasad

lcwc 481 q3

Dec 21st, 2025
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import heapq
  2.  
  3. class Solution:
  4. def minSwaps(self, nums: List[int], forbidden: List[int]) -> int:
  5. n = len(nums)
  6. mapp = defaultdict(lambda:defaultdict(lambda:0))
  7. sameCount = {}
  8. for i in range(n):
  9. numm = nums[i]
  10. forb = forbidden[i]
  11. mapp[forb][numm] += 1
  12. if forb not in sameCount:
  13. sameCount[forb] = 0
  14. if forb == numm:
  15. sameCount[forb]+= 1
  16.  
  17. #lets start collision effect,higher sameCount are the issue for us
  18.  
  19. ordd = []
  20. for k,v in sameCount.items():
  21. heapq.heappush(ordd,[-v,k])
  22.  
  23. #trying to breaking all the bad bonds with
  24. swaps = 0
  25. exitt = 0
  26. while len(ordd)>=2:
  27. bigger = heapq.heappop(ordd)
  28. smaller = heapq.heappop(ordd)
  29. #reverting to original val
  30. bigger[0] = -bigger[0]
  31. smaller[0] = -smaller[0]
  32. subtractor = smaller[0]
  33. remaining = bigger[0]-smaller[0]
  34.  
  35. mapp[smaller[1]][smaller[1]] -= subtractor
  36. mapp[smaller[1]][bigger[1]] += subtractor
  37. mapp[bigger[1]][bigger[1]] -= subtractor
  38. mapp[bigger[1]][smaller[1]] += subtractor
  39.  
  40. swaps += subtractor
  41. if remaining>0:
  42. heapq.heappush(ordd,[-remaining,bigger[1]])
  43. remain = 0
  44. #if still ordd present means there is still one guy having bad bonds
  45. #he needs to be cleanesed meticulously without touching its current nums position or
  46. #without touching its forbidden position
  47. if len(ordd):
  48. rem,target = heapq.heappop(ordd)
  49. rem = -rem
  50. remain = rem
  51. for k,mapi in mapp.items():
  52. if target==k:
  53. continue
  54. for kk,count in mapi.items():
  55. if target==kk:
  56. continue
  57. else:
  58. mini = min(count,rem)
  59. rem -= mini
  60. remain = rem
  61. swaps += mini
  62. if rem<=0:
  63. exitt = 1
  64. break
  65. if exitt == 1:
  66. break
  67.  
  68. if remain>0:
  69. return -1
  70. else:
  71. return swaps
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
Advertisement
Add Comment
Please, Sign In to add comment