Minimum Numbers of Function Calls to Make Target Array - Problem

You are given an integer array target. You have an integer array arr of the same length with all values set to 0 initially.

You also have the following modify function:

  • You can call incrementByOne(arr, i): Increment the value of arr[i] by 1.
  • You can call doubleAll(arr): Double the value of each element in arr.

You want to use the modify function to convert arr to target using the minimum number of calls.

Return the minimum number of function calls to make target from arr.

The test cases are generated so that the answer fits in a 32-bit signed integer.

Input & Output

Example 1 — Basic Operations
$ Input: target = [1,5]
Output: 5
💡 Note: To build [1,5]: Start with [0,0]. Increment arr[0] to get [1,0]. Increment arr[1] to get [1,1]. Double all to get [2,2]. Increment arr[1] to get [2,3]. Double all to get [4,6]. But this is wrong path. Optimal: increment operations = 1+2=3 (from binary 1=1₂, 5=101₂), double operations = max(0,2)=2. Total = 5.
Example 2 — Single Element
$ Input: target = [2]
Output: 2
💡 Note: To build [2]: 2 in binary is 10₂. Need 1 increment operation (one 1-bit) and 1 double operation (bit at position 1). Total = 1 + 1 = 2.
Example 3 — All Zeros
$ Input: target = [0,0]
Output: 0
💡 Note: Array is already [0,0], no operations needed.

Constraints

  • 1 ≤ target.length ≤ 105
  • 0 ≤ target[i] ≤ 109

Visualization

Tap to expand
Minimum Function Calls to Make Target Array INPUT Initial Array (arr): 0 0 i=0 i=1 Target Array: 1 5 Available Operations: incrementByOne(arr, i) doubleAll(arr) target = [1, 5] ALGORITHM STEPS 1 Convert to Binary 1 = 1, 5 = 101 2 Count 1-bits (increments) 1 has 1 bit, 5 has 2 bits 3 Find max bit length Max bits = 3 (from 5) 4 Calculate total calls increments + (maxBits-1) Total increments: 1 + 2 = 3 Doubles needed: 3 - 1 = 2 Total: 3 + 2 = 5 Trace: [0,0]-->[1,0]-->[1,1]--> [2,2]-->[2,3]-->[4,6] err [0,1]-->[0,2]-->[1,4]-->[1,5] 3 inc + 2 dbl = 5 ops FINAL RESULT Minimum Operations: 5 Breakdown: Increments: 3 Doubles: 2 Total: 5 Output: 5 [OK] Verified optimal Key Insight: Work backwards from target: each '1' bit requires an increment, and doubling affects ALL elements simultaneously. The number of doubles needed equals (max bit length - 1) for the largest number. Formula: Total = Sum of popcount(target[i]) + floor(log2(max(target))) TutorialsPoint - Minimum Numbers of Function Calls to Make Target Array | Optimized Greedy with Global Doubling
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
856 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