Minimum Total Cost to Make Arrays Unequal - Problem
Minimum Total Cost to Make Arrays Unequal

You are given two 0-indexed integer arrays nums1 and nums2, both of equal length n. Your mission is to ensure that no element at the same index in both arrays is equal.

You can perform swap operations on nums1 - swap any two elements at indices i and j. The cost of this operation is i + j (sum of the indices).

Goal: Find the minimum total cost to make nums1[i] != nums2[i] for all indices 0 โ‰ค i < n.

Example:
nums1 = [1,2,3,4]
nums2 = [1,2,3,4]
We need to swap elements in nums1 to ensure no position has matching values. If impossible, return -1.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums1 = [1,2,3,4], nums2 = [1,3,2,4]
โ€บ Output: 1
๐Ÿ’ก Note: We swap indices 1 and 2 in nums1. Cost = 1 + 2 = 3. But we can swap indices 1 and 0 with cost = 1, making nums1 = [2,1,3,4]. Now nums1[i] != nums2[i] for all i.
example_2.py โ€” No Solution
$ Input: nums1 = [2,2,2,1], nums2 = [1,2,2,2]
โ€บ Output: -1
๐Ÿ’ก Note: It's impossible to make nums1[i] != nums2[i] for all i. Value 2 appears too frequently in bad positions.
example_3.py โ€” Already Valid
$ Input: nums1 = [1,2,3,4], nums2 = [2,1,4,3]
โ€บ Output: 0
๐Ÿ’ก Note: Arrays already satisfy nums1[i] != nums2[i] for all i, so no swaps needed.

Constraints

  • n == nums1.length == nums2.length
  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค nums1[i], nums2[i] โ‰ค 106
  • Important: The cost of swapping indices i and j is i + j

Visualization

Tap to expand
Array Mismatch Resolution StrategyProblem: Make nums1[i] โ‰  nums2[i] for all inums1: [1, 2, 3, 4, 2]nums2: [1, 3, 3, 4, 2]1BAD2OK3BAD4BAD2BADStep 1: Identify Bad PositionsPositions where values match: [0, 2, 3, 4]These positions MUST be involved in swapsStep 2: Count Value FrequenciesValue 1: appears 1 timeValue 2: appears 1 timeValue 3: appears 1 timeValue 4: appears 1 timeโœ“ No dominant value - all can be pairedStep 3: Calculate Minimum CostTotal cost = sum of all bad positionsCost = 0 + 2 + 3 + 4 = 9Answer: 9
Understanding the Visualization
1
Identify Conflicts
Mark all positions where person matches their unlucky seat
2
Count Problem People
Some people appear in multiple unlucky positions - they need special attention
3
Calculate Help Needed
If one person dominates conflicts, we need extra positions to resolve
4
Minimize Cost
Use positions with lowest indices (cheapest swaps) to resolve all conflicts
Key Takeaway
๐ŸŽฏ Key Insight: The greedy approach works because we must include all conflicting positions in swaps. The challenge is handling cases where one value dominates - requiring strategic use of additional positions to resolve conflicts optimally.
Asked in
Google 12 Meta 8 Amazon 6 Microsoft 4
27.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen