- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 69 lines of Python from the credited upstream file minimum-swaps-to-avoid-forbidden-values.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def minSwaps(self, nums, forbidden):7 """8 :type nums: List[int]9 :type forbidden: List[int]10 :rtype: int11 """12 def boyer_moore_majority_vote(arr):13 result, cnt = None, 014 for x in arr:15 if not cnt:16 result = x17 if x == result:18 cnt += 119 else:20 cnt -= 121 return result22 23 m = boyer_moore_majority_vote((nums[i] for i in xrange(len(nums)) if nums[i] == forbidden[i]))24 cnt = cnt_m = bal = 025 for i in xrange(len(nums)):26 if nums[i] != forbidden[i]:27 if nums[i] != m != forbidden[i]:28 bal += 129 continue30 cnt += 131 if nums[i] != m:32 bal += 133 else:34 bal -= 135 cnt_m += 136 return max(cnt_m, (cnt+1)2) if bal >= 0 else -137 38 394041import collections42 43 4445class Solution2(object):46 def minSwaps(self, nums, forbidden):47 """48 :type nums: List[int]49 :type forbidden: List[int]50 :rtype: int51 """52 cnt1 = collections.defaultdict(int)53 for x in nums:54 cnt1[x] += 155 cnt2 = collections.defaultdict(int)56 for x in forbidden:57 cnt2[x] += 158 if any(cnt1[k]+cnt2[k] > len(nums) for k in cnt1.iterkeys()):59 return -160 cnt3 = collections.defaultdict(int)61 cnt = cnt_m = 062 for i in xrange(len(nums)):63 if nums[i] != forbidden[i]:64 continue65 cnt += 166 cnt3[nums[i]] += 167 cnt_m = max(cnt_m, cnt3[nums[i]])68 return max(cnt_m, (cnt+1)2)69