Minimum Operations to Make Array Values Equal to K - Problem

You are given an integer array nums and an integer k. Your goal is to make all elements in the array equal to k using a special operation.

But first, let's understand the concept of a valid integer:

  • 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], then h = 9 is valid because all elements > 9 are equal to 10, but h = 5 is not valid because elements > 5 include both 8 and 10.

Operation: Select a valid integer h and set all elements greater than h to h.

Return the minimum number of operations required to make every element equal to k, or -1 if it's impossible.

Input & Output

example_1.py โ€” Basic Case
$ Input: {"nums": [2, 11, 10, 1, 3], "k": 1}
โ€บ Output: 4
๐Ÿ’ก Note: We need 4 operations: 11โ†’10 (h=10), 10โ†’3 (h=3), 3โ†’2 (h=2), 2โ†’1 (h=1). Each operation reduces one unique value > k.
example_2.py โ€” Impossible Case
$ Input: {"nums": [1, 2, 3, 4, 5], "k": 10}
โ€บ Output: -1
๐Ÿ’ก Note: Since all elements (1,2,3,4,5) are less than k=10, it's impossible to make them equal to 10 using the allowed operations.
example_3.py โ€” Already Equal
$ Input: {"nums": [5, 5, 5, 5], "k": 5}
โ€บ Output: 0
๐Ÿ’ก Note: All elements are already equal to k=5, so no operations are needed.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • 1 โ‰ค k โ‰ค 106
  • All operations must use valid h values

Visualization

Tap to expand
๐Ÿ—๏ธ Building Height Regulation2111013Target height: k = 1Regulation Strategy1. Buildings > k: {2, 3, 10, 11}2. Each unique height needs 1 regulation3. Process tallest first:11 โ†’ 10 (regulation 1)10 โ†’ 3 (regulation 2)3 โ†’ 2 (regulation 3)2 โ†’ 1 (regulation 4)Total: 4 operationsEach unique height above target requires exactly one regulation!
Understanding the Visualization
1
Survey Buildings
Check all building heights - if any is shorter than target, impossible
2
Identify Unique Heights
Find all unique heights taller than target k
3
Count Regulations
Each unique height > k needs one regulation operation
4
Apply in Order
Process from tallest to shortest for valid regulations
Key Takeaway
๐ŸŽฏ Key Insight: The number of operations equals the number of unique values greater than k. Process them in descending order for valid regulations.
Asked in
Google 35 Amazon 28 Meta 22 Microsoft 18
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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