In this post, I’ll walk through my two solutions to LeetCode Problem 3396: Minimum Number of Operations to Make Elements in Array Distinct, using pythonic a algorithmic approach. Each method has its own strengths, and I explain how I used them to solve the problem cleanly in Python.

🧠 Problem Overview

  • Our goal in this problem is to make all the elements in an array distinct. There is only one operation we can do which is remove the first 3 elements of the array and we need to find minimum number of operations to achieve uniqueness in our array.

First Approach: Pythonic

In this approach, I use the power of **set **to check for uniqueness. A set is a data structure that only contains unique elements, which means if we convert a list to a set, any duplicate elements will automatically be removed.

I keep removing the first 3 elements from the list until the length of the list becomes equal to the length of the set created from it — which means all elements are now distinct.

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        res = 0
        while not len(nums) == len(set(nums)):
            res += 1
            nums = nums[3:]

        return res

✅ Pros:

  • Very readable and short.
  • Makes good use of Python’s built-in features.

⚠️ Cons:

  • Inefficient for large inputs because slicing nums = nums[3:] creates a new list every time (O(n) per operation).
  • Not optimal in terms of performance.

Second Approach: Algorithmic

For a more efficient approach, I switched to using a set to track seen elements and two pointers (i and j). When a duplicate is found, I clear the set and move the window forward by 3 (simulating the removal operation). This gives us better performance, especially on longer arrays.

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        s = set()

        j, i = 0, 0
        while j < len(nums):
            if nums[j] not in s:
                s.add(nums[j])
                j += 1
            else:
                s.clear()
                i += 3
                j = i
        return i // 3

✅ Pros:

  • Efficient: only one pass through the array (O(n) time).

  • Doesn’t create unnecessary intermediate arrays.

  • Scales well for large inputs.

⚠️ Cons:

  • Slightly more code than the Pythonic approach.

  • Requires a bit more thought to understand at first glance.

🧩 Final Thoughts

Both solutions get the job done, but depending on the context (e.g., interview, production code, or learning), one may be preferable over the other. The Pythonic approach shines with its elegance, while the algorithmic one is the go-to when performance matters.