Skip to content

3396. Minimum Number of Operations to Make Elements in Array Distinct 👍

  • Time: $O(n)$
  • Space: $O(100) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int minimumOperations(vector<int>& nums) {
    unordered_set<int> seen;
    for (int i = nums.size() - 1; i >= 0; --i)
      if (!seen.insert(nums[i]).second)
        return (i + 1 + 2) / 3;  // ceil((i + 1) / 3)
    return 0;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int minimumOperations(int[] nums) {
    Set<Integer> seen = new HashSet<>();
    for (int i = nums.length - 1; i >= 0; --i)
      if (!seen.add(nums[i]))
        return (i + 1 + 2) / 3; // ceil((i + 1) / 3)
    return 0;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def minimumOperations(self, nums: list[int]) -> int:
    seen = set()
    for i, num in reversed(list(enumerate(nums))):
      if num in seen:
        return (i + 1 + 2) // 3  # ceil((i + 1) / 3)
      seen.add(num)
    return 0