#1887

Reduction Operations to Make the Array Elements Equal

Medium
ArraySortingHash MapArray
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)

By sorting the array first, we can efficiently determine how many operations are needed to reduce all elements to the smallest value without repeatedly searching for the largest and next largest values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array in non-decreasing order.
  2. 2Step 2: Initialize a variable to count operations and iterate through the array from the second last element to the first.
  3. 3Step 3: For each element, calculate the difference between it and the next element, and add this difference to the operations count.
solution.py6 lines
1def reductionOperations(nums):
2    nums.sort()
3    operations = 0
4    for i in range(len(nums) - 1):
5        operations += nums[i + 1] - nums[i]
6    return operations

Complexity note: The complexity is O(n log n) due to the sorting step, which is more efficient than the brute force approach. The subsequent operations count is O(n).

  • 1Sorting the array allows us to efficiently calculate the number of operations needed.
  • 2The difference between consecutive elements in a sorted array directly gives the number of operations.

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