#1558

Minimum Numbers of Function Calls to Make Target Array

Medium
ArrayGreedyBit ManipulationGreedyBit Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(n log m)Space O(1)

The optimal solution works backwards from nums to arr, using division and counting operations. By halving the numbers when possible, we minimize the number of function calls needed to reach the target.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter for function calls.
  2. 2Step 2: For each number in nums, while it is greater than 0, check if it is even or odd.
  3. 3Step 3: If even, divide by 2 (this counts as one function call). If odd, subtract 1 (this counts as one function call).
  4. 4Step 4: Continue until all numbers in nums are reduced to 0.
solution.py15 lines
1# Full working Python code
2
3def minFunctionCalls(nums):
4    calls = 0
5    for num in nums:
6        while num > 0:
7            if num % 2 == 0:
8                num //= 2
9            else:
10                num -= 1
11            calls += 1
12    return calls
13
14# Example usage
15print(minFunctionCalls([1, 5]))  # Output: 5

Complexity note: This complexity arises because for each number, we may need to perform log m operations (where m is the maximum number in nums) to reduce it to zero.

  • 1Working backwards from the target can simplify the problem.
  • 2Dividing by 2 when possible reduces the number of operations significantly.

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