Taro Logo

Minimum Operations to Make Array Values Equal to K

#3 Most AskedEasy
2 views
Topics:
Arrays

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] to 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.

Example 1:

Input: nums = [5,2,5,4,5], k = 2

Output: 2

Explanation:

The operations can be performed in order using valid integers 4 and then 2.

Example 2:

Input: nums = [2,1,2], k = 2

Output: -1

Explanation:

It is impossible to make all the values equal to 2.

Example 3:

Input: nums = [9,7,5,3], k = 1

Output: 4

Explanation:

The operations can be performed using valid integers in the order 7, 5, 3, and 1.

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= k <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the array contain elements that are strictly less than $k$, and if so, does that immediately make it impossible to achieve the target?
  2. When we replace a value strictly greater than $k$ with a smaller integer of our choice, can we choose that smaller integer to be any value we want (including $k$ or even smaller), or must it be an existing value in the array?
  3. Does replacing all occurrences of a specific value count as a single operation regardless of how many times that value appears in the array?
  4. What are the constraints on the size of the array and the range of values for the elements and $k$?
  5. Are duplicates allowed in the input array, and do identical values larger than $k$ get replaced simultaneously in one operation?

Brute Force Solution

Approach

Imagine you have a collection of items and you want to change every single one of them so they all match a specific target value. The brute force strategy involves testing every possible action you could take on the collection until you either reach your goal or realize it is impossible.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire collection of items to understand their current values.
  2. Check if any item in the collection has a value smaller than your target value, because if it does, it is impossible to reach the goal and you should stop right there.
  3. If all items are greater than or equal to the target value, look for any items that are already equal to the target value and ignore them for now.
  4. Consider every possible number that is smaller than the items you want to change and larger than or equal to the target.
  5. Pretend to pick one of these chosen numbers and imagine reducing all larger items down to match this chosen number.
  6. Count this as one operation, and then check if all items in your collection now match the target value.
  7. If they do not all match the target, repeat the process by picking another possible number to reduce the items further, keeping track of how many operations you are performing.
  8. Exhaustively try every combination of reductions until you find the total number of operations it takes to make everything equal to the target, or determine that you need to count how many distinct reduction steps were necessary.

Code Implementation

def min_operations_to_make_equal_to_k(collection_items, target_value):
    # We must instantly invalidate any scenario where elements fall below our target value
    for current_item in collection_items:
        if current_item < target_value:
            return -1

    # Only distinct values strictly greater than target contribute to necessary operations
    unique_reduction_set = set()

    for current_item in collection_items:
        if current_item > target_value:
            unique_reduction_set.add(current_item)

    # Each distinct value above target requires exactly one coordinated reduction step
    total_operations_count = len(unique_reduction_set)

    return total_operations_count

Big(O) Analysis

Time Complexity
–
Space Complexity
O(N) – The space complexity is driven by the need to store unique elements or count frequencies of the items in the collection, where N is the number of elements in the input array. Specifically, if we use a hash set or hash map to keep track of distinct values greater than the target K, the auxiliary data structure will store at most N unique elements in the worst-case scenario. Therefore, the extra memory required scales linearly with the input size N, leading to an overall auxiliary space complexity of O(N).

Optimal Solution

Approach

To figure out how many operations are needed to bring all numbers down to a target value, we first check if it is even possible by making sure no number starts smaller than the target. If all numbers are valid, we simply count how many unique numbers exist above the target value, because each unique higher value requires one collective step to pull down to the next level.

Here's how the algorithm would work step-by-step:

  1. Check if any starting number is smaller than the target value because if there is one, it is impossible to reach the target and you should immediately stop and report failure.
  2. Gather all the unique numbers that are strictly greater than the target value, ignoring any duplicates since they can all be adjusted together.
  3. Count how many distinct numbers you found that sit above the target.
  4. The final count of these unique higher numbers represents the exact number of operations needed to bring everything down to the target.

Code Implementation

def min_operations_to_reach_target(input_array, target_value):
    # Any number smaller than the target makes it impossible to reduce everything equally.
    for current_number in input_array:
        if current_number < target_value:
            return -1

    # Filtering strictly greater elements isolates the values needing reduction steps.
    greater_numbers = set()
    for current_number in input_array:
        if current_number > target_value:
            greater_numbers.add(current_number)

    # Unique higher values each require one distinct collective operation to pull down.
    total_operations_needed = len(greater_numbers)
    return total_operations_needed

Big(O) Analysis

Time Complexity
O(n) – To analyze the time complexity, let n be the number of elements in the input array. First, we iterate through the array of size n to validate that no element is strictly smaller than the target value. Next, we collect all elements strictly greater than the target into a set to filter out duplicates, which takes linear time proportional to n. Counting the unique elements in the set takes at most n operations since the size of the set cannot exceed n. Summing these linear passes together results in approximately n plus n operations, which simplifies to O(n).
Space Complexity
O(N) – To implement step 2, we gather all unique numbers strictly greater than the target value using a hash set, where N is the total number of elements in the input array. In the worst-case scenario where all elements in the array are distinct and greater than the target, the hash set will store up to N elements. Therefore, the auxiliary space is dominated by this hash set and scales linearly with the input size N. Combining this with the constant amount of memory used for scalar variables, the overall space complexity simplifies to Big O of N.

Edge Cases

An element in the array is strictly less than k
How to Handle:
Return -1 immediately since we can only decrease values greater than k and cannot increase any values to reach k.
All elements in the array are already equal to k
How to Handle:
Return 0 operations because no replacements are needed to satisfy the condition.
Array contains multiple duplicate values greater than k
How to Handle:
Treat all identical values as a single distinct number since replacing one occurrence replaces all of them simultaneously in a single operation.
Input array is empty or null
How to Handle:
Return -1 or 0 depending on problem constraints, but typically an empty array cannot be transformed to contain k and should return -1.
Array contains negative numbers, zeros, and positive numbers mixed with k
How to Handle:
Any value less than k will trigger the impossibility condition and return -1, while values greater than k will be counted as unique reduction steps.
Array has only one element which is strictly greater than k
How to Handle:
Return 1 operation because we can directly replace that single element with k in one step.
Maximum-sized inputs with a large range of distinct values greater than k
How to Handle:
Use a set or sorting approach running in O(N log N) time to count unique elements greater than k efficiently without timing out.
Target k is an extreme boundary value such as minimum or maximum possible integer
How to Handle:
Ensure standard integer types can hold k without underflow or overflow, and rely on standard comparison operators for validation.
0/4 completed