Program to count number of operations required to convert all values into same in Python?

Given a list of integers, you can perform the following operation: pick the largest number and turn it into the second largest number. We need to find the minimum number of operations required to make all integers the same in the list.

For example, if the input is nums = [5, 9, 2], the output will be 3. Here's how: pick 9 first, then make it 5, so array becomes [5, 5, 2]. Then pick 5 and make it 2, getting [5, 2, 2]. Again pick 5 and convert it into 2, resulting in [2, 2, 2].

Algorithm

To solve this problem, we follow these steps:

  • vals − Sort the list of unique values in nums

  • vtoi − Create a mapping where each unique value v maps to its index i

  • Return the sum of vtoi[v] for all values v in nums

Example

Let's implement this solution ?

class Solution:
    def solve(self, nums):
        vals = sorted(set(nums))
        vtoi = {v: i for i, v in enumerate(vals)}
        return sum(vtoi[v] for v in nums)

ob = Solution()
nums = [5, 9, 2]
print(ob.solve(nums))
3

How It Works

The algorithm works by understanding that each number needs to be "reduced" to the smallest number in the array. The number of operations required for each element equals its position in the sorted unique values list.

# Let's trace through the example step by step
nums = [5, 9, 2]

# Step 1: Get unique sorted values
vals = sorted(set(nums))
print("Unique sorted values:", vals)

# Step 2: Create value-to-index mapping
vtoi = {v: i for i, v in enumerate(vals)}
print("Value to index mapping:", vtoi)

# Step 3: Calculate operations for each number
operations = [vtoi[v] for v in nums]
print("Operations for each number:", operations)

# Step 4: Total operations
total = sum(operations)
print("Total operations:", total)
Unique sorted values: [2, 5, 9]
Value to index mapping: {2: 0, 5: 1, 9: 2}
Operations for each number: [1, 2, 0]
Total operations: 3

Alternative Example

Let's test with another example to verify our solution ?

class Solution:
    def solve(self, nums):
        vals = sorted(set(nums))
        vtoi = {v: i for i, v in enumerate(vals)}
        return sum(vtoi[v] for v in nums)

ob = Solution()

# Test with different inputs
test_cases = [
    [1, 1, 1],      # Already same
    [3, 1, 2],      # Different order
    [10, 5, 1, 8]   # More elements
]

for nums in test_cases:
    result = ob.solve(nums)
    print(f"Input: {nums}, Operations: {result}")
Input: [1, 1, 1], Operations: 0
Input: [3, 1, 2], Operations: 3
Input: [10, 5, 1, 8], Operations: 6

Conclusion

The solution efficiently counts operations by mapping each unique value to its rank in sorted order. The total operations equal the sum of these ranks for all elements in the original array.

Updated on: 2026-03-25T12:16:09+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements