Reduction Operations to Make the Array Elements Equal - 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. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
  • Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
  • Reduce nums[i] to nextLargest.

Return the number of operations to make all elements in nums equal.

Input & Output

Example 1 — Basic Reduction
$ Input: nums = [5,1,3]
Output: 3
💡 Note: Step by step: [5,1,3] → [3,1,3] → [1,1,3] → [1,1,1]. Total of 3 operations.
Example 2 — Already Equal
$ Input: nums = [1,1,1]
Output: 0
💡 Note: All elements are already equal, so no operations needed.
Example 3 — Multiple Same Values
$ Input: nums = [1,1,2,2,3]
Output: 4
💡 Note: [1,1,2,2,3] → [1,1,2,2,2] → [1,1,1,2,2] → [1,1,1,1,2] → [1,1,1,1,1]. Total of 4 operations.

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 5 × 104

Visualization

Tap to expand
Reduction Operations to Make Array Elements Equal INPUT nums = [5, 1, 3] 5 i=0 1 i=1 3 i=2 Sorted Unique Values: 1 smallest 3 middle 5 largest Goal: Make all equal to smallest value (1) [1, 1, 1] ALGORITHM STEPS 1 Sort and Count Sort array, track positions 2 Find Operations Each elem needs i steps 3 Sum All Steps Total = sum of indices 4 Return Result Output total operations Operation Trace: Sorted: [1, 3, 5] Index: 0 1 2 1 at idx 0: 0 ops 3 at idx 1: 1 op (3-->1) 5 at idx 2: 2 ops (5-->3-->1) FINAL RESULT Step-by-step reduction: Op 1: 5 --> 3 [5,1,3] --> [3,1,3] Op 2: 3 --> 1 [3,1,3] --> [1,1,3] Op 3: 3 --> 1 [1,1,3] --> [1,1,1] Final Array: 1 1 1 Output: 3 Key Insight: After sorting, each element at index i needs exactly i operations to reach the minimum value. Total operations = sum of all indices = 0 + 1 + 2 = 3. This is O(n log n) time complexity. TutorialsPoint - Reduction Operations to Make the Array Elements Equal | Optimal Solution O(n log n) Time
Asked in
Google 15 Amazon 12 Microsoft 8
38.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen