Minimum Numbers of Function Calls to Make Target Array — LeetCode 1558 Python Solution

MediumGreedyBit ManipulationArray
Problem
#1558
Reading time
2 min

The problem

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

Example

Input
nums = [1,5]
Output
5
Explanation
Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).

Python solution

Python
class Solution:
    def minOperations(self, nums: List[int]) -> int:
        return sum(v.bit_count() for v in nums) + max(0, max(nums).bit_length() - 1)

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Bit Manipulation

Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.

The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array?
LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array is rated Medium on LeetCode.
What topics does LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array cover?
LeetCode 1558. Minimum Numbers of Function Calls to Make Target Array is tagged Greedy, Bit Manipulation and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview