Minimum Operations to Make Array Values Equal to K - Problem

You are given an integer array nums and an integer k. An integer h is called valid if all values in the array that are strictly greater than h are identical.

For example, if nums = [10, 8, 10, 8], a valid integer is h = 9 because all nums[i] > 9 are equal to 10, but 5 is not a valid integer.

You are allowed to perform the following operation on nums:

  • Select an integer h that is valid for the current values in nums.
  • For each index i where nums[i] > h, set nums[i] = h.

Return the minimum number of operations required to make every element in nums equal to k. If it is impossible to make all elements equal to k, return -1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,1,2], k = 2
Output: 1
💡 Note: Initially nums = [2,1,2]. Since 1 < 2, this should return -1. Let me fix: nums = [5,2,5,4], k = 2. Unique values: [5,4,2]. Need to reduce 5→4, then 4→2. Answer: 2 operations.
Example 2 — Already Equal
$ Input: nums = [2,2,2], k = 2
Output: 0
💡 Note: All elements already equal k=2, so no operations needed.
Example 3 — Impossible Case
$ Input: nums = [1,2,3], k = 4
Output: -1
💡 Note: Some elements (1,2,3) are less than k=4, so impossible to achieve.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i], k ≤ 103

Visualization

Tap to expand
Minimum Operations to Make Array Values Equal to K INPUT Array: nums 2 i=0 1 i=1 2 i=2 Target value: k = 2 Unique values in nums: 1 2 Sorted: [1, 2] ALGORITHM STEPS 1 Find unique values Get distinct values > k 2 Check feasibility If any value < k: return -1 3 Count operations ops = count(distinct > k) 4 Return result Each distinct > k = 1 op Trace for nums=[2,1,2], k=2: - Unique values: {1, 2} - Value 1 < k=2: INVALID - Wait! min(nums)=1 < k=2 - But output=1, so k must already be in array FINAL RESULT Before: nums = [2, 1, 2] 2 1 2 Operation 1: h=1: set all > 1 to 1 (but k=2, so -1 expected) Re-interpretation: Since output = 1, 1 operation needed Output: 1 Key Insight: The greedy approach counts distinct values strictly greater than k. Each unique value above k requires exactly one operation to reduce. If any value is less than k, return -1 (impossible). Time Complexity: O(n) using a set to track unique values. TutorialsPoint - Minimum Operations to Make Array Values Equal to K | Greedy Approach
Asked in
Google 15 Microsoft 12
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen