3375. Minimum-Operations-To-Make-Array-Values-Equal-To-K

Question Link

Difficulty: Easy

One of the most confusing descriptions I’ve seen in a while. After reading the question very very very carefully, we can see that there are only 3 cases to consider when comparing the smallest element in nums and k:

  1. If the smallest element in nums is smaller than k, it is not possible to make all values in the array equal to k as there are no operations that increase the value of elements in the array. Therefore, in this case, we return -1
  2. If the smallest element in nums is greater than k, we would need to use 1 operation for each unique element in the list. Therefore, we would need to use len(unique) operations where unique is a list/set of unique elements in nums
  3. If the smallest element in nums is equal to k, we have a similar case to case 2, except we don’t need to use an operation at the end (since k is equal to the smallest element in nums). Therefore, we would need to use len(unique) - 1 operations where unique is a list/set of unique elements in nums
class Solution(object):
    def minOperations(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        unique = set(nums)
        smallest = float('inf')
        for num in unique:
            smallest = min(smallest, num)

        if smallest < k:
            return -1
        if smallest > k:
            return len(unique)

        return len(unique) - 1

Time Complexity: O(n)

Space Complexity: O(n)

Time Taken: 7m 45s