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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Greedy
[1,2,3] [3,2,1]
[4,6,6,5] [4,6,5,5]
[7,7] [8,7]
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)
// }
// 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)
}
# Accepted solution for LeetCode #3785: Minimum Swaps to Avoid Forbidden Values
import collections
from typing import List
#
# @lc app=leetcode id=3785 lang=python3
#
# [3785] Minimum Swaps to Avoid Forbidden Values
#
# @lc code=start
class Solution:
def minSwaps(self, nums: List[int], forbidden: List[int]) -> int:
n = len(nums)
conflict_indices = []
for i in range(n):
if nums[i] == forbidden[i]:
conflict_indices.append(i)
# Feasibility Check
# We need to ensure that for every value v, there are enough valid positions.
# A position i is valid for value v if forbidden[i] != v.
# The number of allowed positions for v is n - count(v in forbidden).
# We must have count(v in nums) <= n - count(v in forbidden).
nums_counts = collections.Counter(nums)
forbidden_counts = collections.Counter(forbidden)
for val, count in nums_counts.items():
if count > n - forbidden_counts[val]:
return -1
if not conflict_indices:
return 0
# If feasible, calculate minimum swaps.
# Let M be the number of conflicts.
# Let max_freq be the maximum frequency of any single value among the conflict values.
# Minimum swaps needed is max(ceil(M / 2), max_freq).
conflict_vals = [nums[i] for i in conflict_indices]
conflict_val_counts = collections.Counter(conflict_vals)
max_freq = 0
if conflict_val_counts:
max_freq = max(conflict_val_counts.values())
m = len(conflict_indices)
# (m + 1) // 2 implements ceil(m / 2) for integers
return max((m + 1) // 2, max_freq)
# @lc code=end
// Accepted solution for LeetCode #3785: Minimum Swaps to Avoid Forbidden Values
// Rust example auto-generated from go reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// 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)
// }
// Accepted solution for LeetCode #3785: Minimum Swaps to Avoid Forbidden Values
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// 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)
// }
Use this to step through a reusable interview workflow for this problem.
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 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.
Review these before coding to avoid predictable interview regressions.
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.
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.
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.