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,8,2]
Output: 1
💡 Note: We can make nums similar to target in one operation: transfer 2 from nums[0] to nums[1] to get [6,8,4,2], which has the same frequencies as target.
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 to Make Arrays Similar INPUT nums = [8, 6, 4, 2] 8 6 4 2 target = [6, 4, 7, 3] 6 4 7 3 Separate by Parity: Even nums: [8,6,4,2] Odd nums: [] Even target: [6,4] Odd target: [7,3] ALGORITHM STEPS 1 Separate by parity Split evens and odds 2 Sort both groups Sort nums and target 3 Match and calculate diff Pair sorted elements 4 Sum positive diffs / 2 Each +2/-2 = 1 operation Matching Process: Sorted nums: [2,4,6,8] Sorted tgt: [3,4,6,7] Diff: 2-3=-1, 4-4=0 6-6=0, 8-7=+1 Positive sum: |+1| = 1 Ops = 1 / 2 * 2 = 1 FINAL RESULT The Operation: Choose i=0, j=3 nums[0]=8-2=6 nums[3]=2+2=4 Before: 8 6 4 2 After: 6 6 4 4 Output 1 Key Insight: Even/odd parity is preserved by +2/-2 operations. We must match evens with evens and odds with odds separately. Sorting both arrays ensures optimal greedy matching. Total ops = sum of positive differences / 2 (since each op moves 2 units between two elements). TutorialsPoint - Minimum Number of Operations to Make Arrays Similar | Greedy Matching (Even/Odd Separation)
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