Watch 10 video solutions for Minimum Swaps to Avoid Forbidden Values, a hard level problem involving Array, Hash Table, Greedy. This walkthrough by Rajan Keshari ( CSE - IIT Dhanbad ) has 1,248 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
You are given two integer arrays, nums and forbidden, each of length n.
You may perform the following operation any number of times (including zero):
i and j, and swap nums[i] with nums[j].Return the minimum number of swaps required such that, for every index i, the value of nums[i] is not equal to forbidden[i]. If no amount of swaps can ensure that every index avoids its forbidden value, return -1.
Example 1:
Input: nums = [1,2,3], forbidden = [3,2,1]
Output: 1
Explanation:
One optimal set of swaps:
i = 0 and j = 1 in nums and swap them, resulting in nums = [2, 1, 3].i, nums[i] is not equal to forbidden[i].Example 2:
Input: nums = [4,6,6,5], forbidden = [4,6,5,5]
Output: 2
Explanation:
One optimal set of swaps:i = 0 and j = 2 in nums and swap them, resulting in nums = [6, 6, 4, 5].i = 1 and j = 3 in nums and swap them, resulting in nums = [6, 5, 4, 6].i, nums[i] is not equal to forbidden[i].Example 3:
Input: nums = [7,7], forbidden = [8,7]
Output: -1
Explanation:
It is not possible to makenums[i] different from forbidden[i] for all indices.Example 4:
Input: nums = [1,2], forbidden = [2,1]
Output: 0
Explanation:
No swaps are required because nums[i] is already different from forbidden[i] for all indices, so the answer is 0.
Constraints:
1 <= n == nums.length == forbidden.length <= 1051 <= nums[i], forbidden[i] <= 109Problem Overview: You are given an array and a list of forbidden values for each index. The goal is to rearrange the array using the minimum number of swaps so that nums[i] never equals the forbidden value for that position. If multiple positions violate the rule, you must strategically swap elements so both indices become valid.
Approach 1: Brute Force Swap Checking (O(n²) time, O(1) space)
Scan the array and collect indices where nums[i] equals the forbidden value. For every such index i, try swapping with every other index j and check whether both positions become valid after the swap. This requires simulating swaps and validating conditions repeatedly. The approach works for small inputs but becomes slow because every bad position may attempt up to n candidate swaps. It’s mainly useful to understand the constraints before optimizing.
Approach 2: Greedy with Hash Counting (O(n) time, O(n) space)
Track positions where the constraint is violated using a simple scan. Maintain a frequency map of values and record indices where nums[i] == forbidden[i]. The key insight: a swap fixes two positions if each element is acceptable in the other’s index. Using a hash table, quickly locate candidate indices whose values resolve the conflict. Pair up incompatible positions greedily so one swap fixes both. When direct pairing isn’t possible, route through an intermediate index whose value is valid in both positions. This reduces unnecessary swaps and guarantees minimal operations in most cases.
Approach 3: Counting Conflicts and Cycle Resolution (O(n) time, O(n) space)
Model the problem as a mismatch graph. Each index with a forbidden conflict points to the position where its value can legally go. These mappings form cycles similar to permutation correction. Using ideas from array rearrangement and greedy placement, each cycle of length k requires k-1 swaps. Build a mapping from values to indices and resolve cycles while marking visited nodes. This method guarantees minimal swaps because every swap moves an element closer to a valid position.
Recommended for interviews: The greedy counting or cycle-based solution is what interviewers expect. Brute force demonstrates the core constraint—identifying forbidden matches—but it does not scale. The optimal solution shows that you recognize the structure of mismatches and reduce the problem to pairing or resolving permutation cycles in linear time.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Swap Checking | O(n²) | O(1) | Useful for understanding constraints or very small arrays |
| Greedy with Hash Counting | O(n) | O(n) | General case; quickly pairs conflicting positions using hash lookups |
| Cycle Resolution on Mismatches | O(n) | O(n) | Best when swaps form permutation-like cycles and minimal swaps must be guaranteed |