LeetCode #3785 — HARD

Minimum Swaps to Avoid Forbidden Values

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

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 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:

  • Select indices i = 0 and j = 1 in nums and swap them, resulting in nums = [2, 1, 3].
  • After this swap, for every index 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:
  • Select indices i = 0 and j = 2 in nums and swap them, resulting in nums = [6, 6, 4, 5].
  • Select indices i = 1 and j = 3 in nums and swap them, resulting in nums = [6, 5, 4, 6].
  • After these swaps, for every index 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 make nums[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 <= 105
  • 1 <= nums[i], forbidden[i] <= 109
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Hash Map · Greedy

Example 1

[1,2,3]
[3,2,1]

Example 2

[4,6,6,5]
[4,6,5,5]

Example 3

[7,7]
[8,7]
Step 02

Core Insight

What unlocks the optimal approach

  • Solve the problem greedily.
  • Count combined frequencies of values in <code>nums</code> and <code>forbidden</code> into a map <code>freq</code>.
  • If any <code>freq[val] >= n + 1</code> return <code>-1</code> (impossible).
  • Collect bad positions (<code>nums[i] == forbidden[i]</code>) into a map <code>badPairs[val]</code> counts.
  • Let <code>badPairsSum</code> be the sum of all bad counts and <code>maxBadPairs</code> the maximum bad count for any single value.
  • The minimum swaps equals <code>max((badPairsSum + 1) / 2, maxBadPairs)</code> (i.e. ceil(badPairsSum/2) vs the largest same-value bad cluster).
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3785: Minimum Swaps to Avoid Forbidden Values
// Auto-generated Java example from go.
class Solution {
    public void exampleSolution() {
    }
}
// Reference (go):
// // Accepted solution for LeetCode #3785: Minimum Swaps to Avoid Forbidden Values
// package main
// 
// // https://space.bilibili.com/206214
// func minSwaps(nums, forbidden []int) int {
// 	n := len(nums)
// 	total := map[int]int{}
// 	for _, x := range nums {
// 		total[x]++
// 	}
// 
// 	cnt := map[int]int{}
// 	k, mx := 0, 0
// 	for i, x := range forbidden {
// 		total[x]++
// 		if total[x] > n {
// 			return -1
// 		}
// 		if x == nums[i] {
// 			k++
// 			cnt[x]++
// 			mx = max(mx, cnt[x])
// 		}
// 	}
// 
// 	return max((k+1)/2, mx)
// }
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n log n)
Space
O(1)

Approach Breakdown

EXHAUSTIVE
O(2ⁿ) time
O(n) space

Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.

GREEDY
O(n log n) time
O(1) space

Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.

Shortcut: Sort + single pass → O(n log n). If no sort needed → O(n). The hard part is proving it works.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

Using greedy without proof

Wrong move: Locally optimal choices may fail globally.

Usually fails on: Counterexamples appear on crafted input orderings.

Fix: Verify with exchange argument or monotonic objective before committing.