Minimum Number of Operations to Make Arrays Similar - Problem

You are given two positive integer arrays nums and target, of the same length.

In one operation, you can choose any two distinct indices i and j where 0 <= i, j < nums.length and:

  • set nums[i] = nums[i] + 2 and
  • set nums[j] = nums[j] - 2.

Two arrays are considered to be similar if the frequency of each element is the same.

Return the minimum number of operations required to make nums similar to target. The test cases are generated such that nums can always be similar to target.

Input & Output

Example 1 — Basic Case
$ Input: nums = [8,6,4,2], target = [6,4,7,3]
Output: 1
💡 Note: We can make nums similar to target in one operation: nums[0] -= 2 and nums[1] += 2 to get [6,8,4,2]. Then rearrange to match target frequencies.
Example 2 — No Operations Needed
$ Input: nums = [1,2,3,4], target = [2,1,4,3]
Output: 0
💡 Note: nums and target already have the same frequency of each element: one 1, one 2, one 3, one 4. No operations needed.
Example 3 — Multiple Operations
$ Input: nums = [1,1,1,1], target = [1,1,9,9]
Output: 4
💡 Note: Need to convert two 1's to 9's. Each 1→9 requires 4 operations: 1→3→5→7→9. But we do it optimally by transferring from one element to another.

Constraints

  • n == nums.length == target.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i], target[i] ≤ 106
  • nums and target have the same sum

Visualization

Tap to expand
Minimum Operations: Parity Preservation KeyInput: nums = [8,6,4,2]target = [6,4,7,3]Operation: nums[i] ± 2, nums[j] ∓ 2Preserves parity (even/odd)Even: [8,6,4,2]OperationsTransfer +/−Target: [6,4,7,3]Sort: [2,4,6,8]Sort: [4,6,7,3]Result: 1 Operation NeededGreedy matching minimizes total operations
Understanding the Visualization
1
Input Arrays
nums = [8,6,4,2], target = [6,4,7,3]
2
Parity Insight
Operations ±2 preserve even/odd nature
3
Greedy Matching
Sort and match within parity groups
Key Takeaway
🎯 Key Insight: Operations preserve parity, so we can solve even and odd numbers independently using greedy matching
Asked in
Google 15 Meta 12 Amazon 8
23.4K Views
Medium Frequency
~25 min Avg. Time
856 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