Reduction Operations to Make the Array Elements Equal — LeetCode 1887 Python Solution
MediumArraySorting
- Problem
- #1887
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
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
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 \times \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.