Minimum Swaps to Avoid Forbidden Values - Solution & Explanation
Problem Statement
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):
- Choose two distinct indices
iandj, and swapnums[i]withnums[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:
- Select indices
i = 0andj = 1innumsand swap them, resulting innums = [2, 1, 3]. - After this swap, for every index
i,nums[i]is not equal toforbidden[i].
Example 2:
Input: nums = [4,6,6,5], forbidden = [4,6,5,5]
Output: 2
Explanation:
One optimal set of swaps:- Select indices
i = 0andj = 2innumsand swap them, resulting innums = [6, 6, 4, 5]. - Select indices
i = 1andj = 3innumsand swap them, resulting innums = [6, 5, 4, 6]. - After these swaps, for every index
i,nums[i]is not equal toforbidden[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] <= 109
Approach Overview
Problem 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.
Solutions for this problem are being prepared.
Try solving it yourselfDetailed Complexity Analysis
| 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 |
Video Solution
Leetcode Weekly Contest 481 || Q3. Minimum Swaps to Avoid Forbidden Values || Pigeonhole || Watch2X🚀 • Rajan Keshari ( CSE - IIT Dhanbad ) • 1,289 views views
Watch 9 more video solutions →Frequently Asked Questions
Is Minimum Swaps to Avoid Forbidden Values easy or hard?
Minimum Swaps to Avoid Forbidden Values Python/Java solution
How to solve Minimum Swaps to Avoid Forbidden Values in O(n)?
What is the best approach for Minimum Swaps to Avoid Forbidden Values?
Is Minimum Swaps to Avoid Forbidden Values asked at Google/Amazon/Meta?
What data structure is used in Minimum Swaps to Avoid Forbidden Values?
What is the time complexity of Minimum Swaps to Avoid Forbidden Values?
Ready to solve this problem?
Practice Minimum Swaps to Avoid Forbidden Values with our built-in code editor and test cases.
Practice on FleetCode