Minimum Number of Operations to Make Arrays Similar - Problem
Array Transformation Challenge: Transform one array to have the same frequency distribution as another using balanced operations!

You're given two positive integer arrays nums and target of equal length. Your mission is to make them similar - meaning they should have the same frequency of each element (like anagrams for arrays).

The Rules:
• In each operation, pick two different indices i and j
• Add 2 to nums[i] and subtract 2 from nums[j]
• Each operation maintains the total sum (it's balanced!)

Goal: Find the minimum number of operations to make nums similar to target.

Key Insight: Since we can only add/subtract 2, the parity (odd/even nature) of each element never changes! This is crucial for solving efficiently.

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,3,5,2], target = [1,6,2,5]
Output: 2
💡 Note: We need 2 operations: First separate by parity - evens: [4,2] → [6,2], odds: [3,5] → [1,5]. For evens: 4→6 needs 1 operation. For odds: 3→1 needs 1 operation. Total: 2 operations.
example_2.py — Already Similar
$ Input: nums = [1,2,3,4], target = [4,3,2,1]
Output: 0
💡 Note: The arrays already have the same frequency of each element (just different order), so they are already similar. No operations needed.
example_3.py — Complex Transformation
$ Input: nums = [8,7,6,5], target = [2,3,10,11]
Output: 6
💡 Note: Separate by parity - evens: [8,6] → [2,10], odds: [7,5] → [3,11]. For evens: 8→2 needs 3 ops, 6→10 needs 2 ops (but 6→10 means we need extra from the 8→2). For odds: 7→3 needs 2 ops, 5→11 needs 3 ops (but we have excess from 7→3). Total operations: 6.

Constraints

  • n == nums.length == target.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i], target[i] ≤ 106
  • The test cases are generated such that nums can always be made similar to target

Visualization

Tap to expand
🚰 Water Redistribution AnalogyOdd Capacity Containers3L5LTarget: 1L, 5LEven Capacity Containers2L4LTarget: 2L, 6L2L transfer1 operation2L transfer1 operation💡 Key InsightContainer types preserved by 2L transfersSolve odd and even groups independentlyTotal: 2 operations
Understanding the Visualization
1
Separate Container Types
Group containers by capacity type (odd vs even liters)
2
Sort by Capacity
Arrange containers from smallest to largest capacity in each group
3
Greedy Matching
Transfer excess water from overfull to underfull containers optimally
4
Count Transfers
Each 2-liter transfer represents one operation
Key Takeaway
🎯 Key Insight: Parity constraints split the problem into two independent subproblems, making a complex transformation problem solvable with simple greedy matching!
Asked in
Google 35 Meta 28 Amazon 22 Microsoft 18
38.5K Views
Medium Frequency
~25 min Avg. Time
1.4K 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