#3375

Minimum Operations to Make Array Values Equal to K

Easy
ArrayHash TableHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution takes advantage of the fact that we can directly count how many operations are needed by focusing on the unique values in the array. We only need to consider values greater than k and how many operations it takes to reduce them to k.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a frequency map of the numbers in nums.
  2. 2Step 2: If any number in nums is less than k, return -1 immediately.
  3. 3Step 3: Initialize operations to 0 and iterate through the unique values in descending order.
  4. 4Step 4: For each value greater than k, add its frequency to operations.
  5. 5Step 5: Return the total operations.
solution.py12 lines
1# Full working Python code
2
3def min_operations(nums, k):
4    from collections import Counter
5    freq = Counter(nums)
6    if any(num < k for num in nums):
7        return -1
8    operations = 0
9    for num in sorted(freq.keys(), reverse=True):
10        if num > k:
11            operations += freq[num]
12    return operations

Complexity note: The complexity is O(n) because we traverse the array a couple of times (once for frequency counting and once for calculating operations), leading to linear time complexity.

  • 1We can only reduce numbers greater than k.
  • 2If any number is less than k, it's impossible to make all equal to k.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.