Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 8, 2025 23:24
Show Gist options
  • Save Ifihan/85904221bc8986d8b8ef272ebcad2eab to your computer and use it in GitHub Desktop.
Save Ifihan/85904221bc8986d8b8ef272ebcad2eab to your computer and use it in GitHub Desktop.
Minimum Number of Operations to Make Elements in Array Distinct

Question

Approach

I started from index 0 and checked for duplicates using a frequency counter. If duplicates existed, I removed the first 3 elements (or all if fewer than 3) and counted one operation. I repeated this until all remaining elements were distinct, or the array was empty.

Implementation

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        ops = 0
        
        while True:
            freq = Counter(nums)
            if all(v == 1 for v in freq.values()):
                break
            nums = nums[3:] if len(nums) >= 3 else []
            ops += 1
        return ops

Complexities

  • Time: O(n^2)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment