We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reduction Operations to Make the Array Elements Equal

Number: 2016

Difficulty: Medium

Paid? No

Companies: Microsoft


Problem Description

Given an integer array nums, the task is to make all elements equal by repeatedly performing the following operation: identify the largest element (choosing the smallest index if there are ties), then reduce this element to the next largest value that is strictly smaller. Return the total number of operations required to make every element in nums equal.


Key Insights

  • Sorting the array simplifies the identification of distinct values.
  • The smallest element in the sorted array is the final target value.
  • Each distinct value (from smallest to largest) contributes operations equal to the number of elements that are above that value.
  • Rather than simulating each operation, count the reductions needed by iterating through the sorted array and accumulating a running count of distinct values encountered.

Space and Time Complexity

Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) if the sorting algorithm requires extra space; O(1) additional space if an in-place sort is used.


Solution

The solution starts by sorting the array in ascending order. Once sorted, the smallest element is the target value for all elements. For each element starting from the second one, we check if it is different from the previous element. If so, a new distinct (larger) value is found, and we increment a counter representing the number of distinct values encountered so far. Each element will eventually have to be reduced as many times as the number of distinct values that are less than it. By summing these counts, we obtain the total number of operations required. This method efficiently calculates the answer without simulating the individual reduction operations.


Code Solutions

# Python Implementation

def reductionOperations(nums):
    # Sort the list to group identical values and identify distinct values
    nums.sort()
    operations = 0
    distinct_count = 0  # Counter for distinct values encountered

    # Traverse the sorted list from the second element onward
    for i in range(1, len(nums)):
        # Check if the current element is a new distinct number
        if nums[i] != nums[i - 1]:
            distinct_count += 1
        # For each element, add the current distinct count to operations
        operations += distinct_count

    return operations

# Example test cases
print(reductionOperations([5, 1, 3]))      # Expected output: 3
print(reductionOperations([1, 1, 1]))      # Expected output: 0
print(reductionOperations([1, 1, 2, 2, 3]))  # Expected output: 4
← Back to All Questions