Minimum Operations to Make All Array Elements Equal — LeetCode 2602 Python Solution
MediumArrayBinary SearchPrefix SumSorting
- Problem
- #2602
- Pattern
- Prefix Sum
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an array nums consisting of positive integers. You are also given an integer array queries of size m.
Example
- Input
- nums = [3,1,6,8], queries = [1,5]
- Output
- [14,10]
- Explanation
- For the first query we can do the following operations:
Python solution
Python
class Solution:
def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
s = list(accumulate(nums, initial=0))
ans = []
for x in queries:
i = bisect_left(nums, x + 1)
t = s[-1] - s[i] - (len(nums) - i) * x
i = bisect_left(nums, x)
t += x * i - s[i]
ans.append(t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 2602. Minimum Operations to Make All Array Elements Equal is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
LeetCode 1889Minimum Space Wasted From PackagingHardLeetCode 2389Longest Subsequence With Limited SumEasyLeetCode 2448Minimum Cost to Make Array EqualHardLeetCode 354Russian Doll EnvelopesHardLeetCode 363Max Sum of Rectangle No Larger Than KHardLeetCode 378Kth Smallest Element in a Sorted MatrixMedium
Frequently asked questions
- How hard is LeetCode 2602. Minimum Operations to Make All Array Elements Equal?
- LeetCode 2602. Minimum Operations to Make All Array Elements Equal is rated Medium on LeetCode.
- What topics does LeetCode 2602. Minimum Operations to Make All Array Elements Equal cover?
- LeetCode 2602. Minimum Operations to Make All Array Elements Equal is tagged Array, Binary Search, Prefix Sum and Sorting on LeetCode.