Reduction Operations to Make the Array Elements Equal - Problem

Imagine you have an array of integers where some elements are larger than others. Your mission is to level the playing field by making all elements equal through a series of strategic reduction operations.

Here's how the reduction process works:

  1. Identify the tallest tower: Find the largest value in the array. If multiple elements share this maximum value, choose the one with the smallest index.
  2. Find the next step down: Locate the next largest value that is strictly smaller than your current maximum.
  3. Make the reduction: Replace the maximum value with this next largest value.

Repeat this process until all elements in the array are equal. Your task is to determine how many operations this will take.

Example: Given [5, 1, 3], you'd first reduce 5→3 (1 operation), then 3→1 (1 operation), then 3→1 again (1 operation), for a total of 3 operations.

Input & Output

example_1.py — Basic Case
$ Input: nums = [5, 1, 3]
Output: 3
💡 Note: First reduce 5→3 (1 op), then reduce first 3→1 (1 op), finally reduce second 3→1 (1 op). Total: 3 operations.
example_2.py — Multiple Duplicates
$ Input: nums = [1, 1, 1]
Output: 0
💡 Note: All elements are already equal, so no operations are needed.
example_3.py — Complex Case
$ Input: nums = [1, 1, 2, 2, 3]
Output: 4
💡 Note: Reduce 3→2 (1 op), then reduce 2→1 three times (3 ops). Total: 4 operations.

Visualization

Tap to expand
Mountain Peak Reduction VisualizationOriginal Heights: [5, 1, 3, 1, 3]51313Reduction AnalysisHeight 5 → 3: 1 peakElements passing through: 1Operations: 1Height 3 → 1: 2 peaks + 1 from aboveElements passing through: 3Operations: 3Height 1: Final destinationNo further reductions neededOperations: 0Total Operations: 4(1 + 3 = 4)🎯 Key insight: Count elements that must "flow down" through each height level
Understanding the Visualization
1
Survey the Landscape
Count how many peaks exist at each height level
2
Plan the Reductions
Determine how many peaks must pass through each reduction level
3
Calculate Total Work
Sum up all the individual reduction operations needed
Key Takeaway
🎯 Key Insight: Instead of simulating each operation, calculate how many elements must pass through each height level during the reduction process.

Time & Space Complexity

Time Complexity
⏱️
O(n²)

In worst case, we need O(n) operations, and each operation requires O(n) time to find max and next largest

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track current state

n
2n
Linear Space

Constraints

  • 1 ≤ nums.length ≤ 5 × 104
  • 1 ≤ nums[i] ≤ 5 × 104
  • All operations must be performed as described
Asked in
Amazon 35 Google 28 Microsoft 22 Meta 18
26.7K Views
Medium Frequency
~18 min Avg. Time
890 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