MediumNo. 1887

Reduction Operations to Make the Array Elements Equal — LeetCode 1887 Python Solution

Pattern
Sorting
Topics
Array, Sorting
Reading time
2 min

The problem

Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps: Find the largest value in nums.

Example

Input
nums = [5,1,3]
Output
3
Explanation
It takes 3 operations to make all elements in nums equal:

Python solution

PythonSolution
class Solution:
    def reductionOperations(self, nums: List[int]) -> int:
        nums.sort()
        ans = cnt = 0
        for a, b in pairwise(nums):
            if a != b:
                cnt += 1
            ans += cnt
        return ans

Complexity

Time
O(n × log n)
Space · auxiliary
O(log n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1887. Reduction Operations to Make the Array Elements Equal is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0056Merge IntervalsMedium
0164Maximum GapMedium
0274H-IndexMedium
0406Queue Reconstruction by HeightMedium
0414Third Maximum NumberEasy
0462Minimum Moves to Equal Array Elements IIMedium

Frequently asked questions

How hard is LeetCode 1887. Reduction Operations to Make the Array Elements Equal?

LeetCode 1887. Reduction Operations to Make the Array Elements Equal is rated Medium on LeetCode.

What is the time complexity of LeetCode 1887. Reduction Operations to Make the Array Elements Equal?

The Python solution on this page runs in O(n × log n).

What is the space complexity of LeetCode 1887. Reduction Operations to Make the Array Elements Equal?

The Python solution on this page uses O(log n) auxiliary space.

What topics does LeetCode 1887. Reduction Operations to Make the Array Elements Equal cover?

LeetCode 1887. Reduction Operations to Make the Array Elements Equal is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.