Leetcode 1558. Minimum Numbers of Function Calls to Make Target Array

Problem Explanation:

Given an array of integers, you are supposed to transform an array of the same size full of zeros into this array, following two possible operations:

  1. Increment an element by 1.
  2. Double all elements in the array.

The task is to calculate and return the minimum number of these operations that must be performed to transform the array of zeros into the target array.

Let's go through an example to understand better:

Example:

Consider nums = [1,5]

  1. Increment the second element by 1: array changes from [0, 0] to get [0, 1]. This is 1 operation.
  2. Double all the elements: array changes from [0, 1] -> [0, 2] -> [0, 4]. These are 2 operations.
  3. Increment the elements by 1: array changes from [0, 4] -> [1, 4] -> [1, 5]. These are 2 operations.

Total number of operations are: 1 + 2 + 2 = 5.

Algorithm

The key observations here are:

  1. An increment operation can only affect a single number, while a doubling operation affects all numbers.
  2. Increment operations always precede doubling operations.

Given these, it is clear that each number in the array will require an "increment operation" equivalent to its bit value count. This follows from the fact that each increment operation contributes to flipping a '0' bit to '1' bit in the binary representation. Furthermore, the maximum number of doubling operations a number can have is the position of the "highest bit" or the maximum power of 2 available in each number in the array representation.

So algorithmically speaking:

  1. Calculate the number of "1" bits.
  2. Calculate the position of the "highest bit".

Sum these up to get the minimum operations required to transform the array of zero's to the provided array.

Python Solution

1
2python
3class Solution:
4    def minOperations(self, nums: List[int]) -> int:
5        max_bits = max_pop = 0
6        # Go through each number in the array
7        for num in nums:
8            # get the binary representation of the number
9            bin_num = bin(num)[2:]
10            # Determine the max bits and the number of "1s" in the binary representation.
11            max_bits = max(max_bits, len(bin_num))
12            max_pop +=  bin_num.count('1')
13        return max_bits + max_pop

Java Solution

1
2java
3class Solution {
4    public int minOperations(int[] nums) {
5        int maxBits = 0, maxPop = 0;
6        for (int num : nums) {
7            String binNum = Integer.toBinaryString(num);
8            maxBits = Math.max(maxBits, binNum.length());
9            maxPop += binNum.chars().filter(ch -> ch == '1').count();
10        }
11        return maxBits + maxPop;
12    }
13}

Javascript Solution

1
2javascript
3var minOperations = function(nums) {
4        var max_bits = 0, max_pop = 0;
5        nums.forEach((num) => {
6        var bin_num = num.toString(2);
7        max_bits = Math.max(max_bits, bin_num.length);
8        max_pop += Array.from(bin_num).filter(ch => ch == '1').length;
9    });
10    return max_bits + max_pop;
11};

C++ Solution

1
2c++
3class Solution {
4public:
5    int minOperations(vector<int>& nums) {
6        int max_bits = 0, max_pop = 0;
7        for (auto &num : nums) {
8            bitset<32> b(num);
9            max_bits = max(max_bits, 31 - __builtin_clz(num));
10            max_pop +=  b.count();
11        }
12        return max_bits + 1 + max_pop;
13    }
14};

C# Solution

1
2csharp
3public class Solution {
4    public int MinOperations(int[] nums) {
5        int max_bits = 0, max_pop = 0;
6        foreach(var num in nums){
7            string bin_num = Convert.ToString(num, 2);
8            max_bits = Math.Max(max_bits, bin_num.Length);
9            max_pop +=  bin_num.Count(c => c == '1');
10        }
11        return max_bits + max_pop;
12    }
13}

For all these solutions, the time complexity is O(N), where N is the size of nums array, because for each element in the array we perform a certain set of operations. The space complexity is O(1) as there is no extra space being used that scales with input size.By counting the number of '1' bits and the position of the "highest bit", we can determine the minimum number of steps required to transform an array of zeros into our target array. In each language solution, the code loops through the array and represents each number in binary. From this binary representation, it is straightforward to determine and count the '1' bits and calculate the maximum position where '1' appears.

The Python solution shows an elegant usage of built-in Python functions. The bin function returns a binary representation of the number. max function is used to track the highest bit position, and count function helps in keeping a tally of '1' bits occurring in the binary representation.

In the Java solution, we see a similar approach. Integer.toBinaryString(num) is used to get binary representation. Java's Math.max is used to keep track of the highest bit position, and the filter method chain is used to count '1' bits.

The Javascript solution again is similar to the Python and Java ones. The number is converted to a binary representation using toString(2). The tally of '1' bits is kept using Javascript's Array.from and filter methods to convert the binary string into an array and count '1' bits.

The C++ solution uses the bitset<32> to keep the binary representation of numbers. The __builtin_clz function is a GCC built-in function which returns the leading zero count, flipping this gives the position of the highest bit. The '1' bits are counted using b.count().

In the C# solution, Convert.ToString(num, 2) is used to convert the number to binary. Math.Max is used to keep track of the max bit position and bin_num.Count(c => c == '1') is used to count the total number of '1' bits in the binary representation.

In conclusion, this problem highlights the importance of understanding binary operations and bit manipulation in efficient problem solving and coding. Furthermore, it demonstrates how a good understanding of the built-in functions provided by each language can lead to elegant and efficient solutions.


Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ