1 minute read

Problem Statement

problem

Intuition

The problem requires minimizing operations to ensure all elements in the list nums are at least k. The key observation is that we can iteratively combine the two smallest numbers to form a larger number, leveraging a min-heap for efficiency.

Approach

  1. Use a Min-Heap: Convert the list nums into a min-heap using heapq.heapify(nums), allowing us to efficiently extract the smallest two elements.
  2. Iterate Until Condition is Met: While there are at least two elements in nums:
    • Extract the two smallest elements x and y.
    • If both x and y are greater than or equal to k, return the operation count.
    • Otherwise, combine them using the formula min(x, y) * 2 + max(x, y), and push the result back into the heap.
    • Increment the operation counter.
  3. Return the Operation Count: If we exhaust the heap before all elements reach k, return the count of operations performed.

Complexity

  • Time Complexity:

    • Heap operations (heapify, heappop, and heappush) take O(log n), and we perform these up to O(n) times.
    • Overall complexity: O(n log n).
  • Space Complexity:

    • The heap is stored in place, so the space complexity is O(1) (excluding input storage).

Code

import heapq
from typing import List

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        heapq.heapify(nums)
        ops = 0
        while len(nums) >= 2:
            x = heapq.heappop(nums)
            y = heapq.heappop(nums)
            if x >= k and y >= k:
                return ops

            heapq.heappush(nums, min(x, y) * 2 + max(x, y))
            ops += 1
        return ops

Editorial

Approach: Priority Queue

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        heapq.heapify(nums)

        num_operations = 0
        while nums[0] < k:
            x = heapq.heappop(nums)
            y = heapq.heappop(nums)
            heapq.heappush(nums, min(x, y) * 2 + max(x, y))

            num_operations += 1

        return num_operations
  • time: O(nlogn)
  • space: O(n)