Skip to content

← leetcode

Minimum Number of Operations to Make Elements in Array Distinct

· Easy

LeetCode problem 3396

The answer can be simplified down to:

  • if there is any number in nums such that nums[i] < k, return -1
  • else, return the number of unique integers inside nums minus 1

code

class Solution {
public:
    int minOperations(vector<int>& nums, int k) {
        int mp[101] = {0};
        int ans = 0;
        for (int num : nums) {
            if (num < k) return -1;
            if (mp[num] == 0) {
                ++ans;
                mp[num] = 1;
            }
        }
        if (mp[k] == 0) ++ans;
        return ans-1;
    }
};

complexity

  • Time: O(n)
  • Space: O(n)