#3785
Minimum Swaps to Avoid Forbidden Values
HardArrayHash TableGreedyCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Count occurrences of forbidden values and find minimum swaps needed to replace them with non-forbidden values.
⚙️
Algorithm
3 steps- 1Step 1: Count frequency of each value in nums and forbidden.
- 2Step 2: Identify values in nums that match forbidden values and need to be swapped.
- 3Step 3: Calculate minimum swaps needed to replace forbidden values with non-forbidden values.
solution.py10 lines
1def min_swaps_optimal(nums, forbidden):
2 from collections import Counter
3 freq = Counter(nums)
4 forbidden_count = Counter(forbidden)
5 swaps = 0
6 for num in forbidden:
7 if freq[num] > 0:
8 swaps += 1
9 freq[num] -= 1
10 return swaps if swaps <= len(nums) else -1ℹ
Complexity note: This complexity is linear since we only traverse the arrays a couple of times.
- 1Count occurrences to identify swaps needed.
- 2Focus on replacing forbidden values with alternatives.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.