#2449

Minimum Number of Operations to Make Arrays Similar

Hard
ArrayGreedySortingGreedySortingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach sorts both arrays and calculates the difference in values. By focusing on the excess and deficit of values, we can efficiently determine how many operations are needed to balance the two arrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort both nums and target arrays.
  2. 2Step 2: Separate the excess and deficit values for both arrays based on their differences.
  3. 3Step 3: Calculate the total excess and deficit, and divide by 2 to find the number of operations needed.
solution.py14 lines
1# Full working Python code
2
3def min_operations(nums, target):
4    nums.sort()
5    target.sort()
6    excess = 0
7    deficit = 0
8    for n, t in zip(nums, target):
9        if n > t:
10            excess += (n - t) // 2
11        elif n < t:
12            deficit += (t - n) // 2
13    return max(excess, deficit)
14

Complexity note: The sorting step dominates the time complexity, making it O(n log n), while we only use a constant amount of extra space for counters.

  • 1Separating excess and deficit values helps in understanding how many operations are needed.
  • 2Sorting both arrays allows for a structured way to compare and balance values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.