#2835

Minimum Operations to Form Subsequence With Target Sum

Hard
ArrayGreedyBit ManipulationGreedyBit Manipulation
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal approach focuses on the bits of the target and uses a greedy strategy to break down larger powers of 2 into smaller ones until we can form the target sum. This is efficient because it reduces the problem size significantly with each operation.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count occurrences of each power of 2 in nums.
  2. 2Step 2: For each bit in the target (from least to most significant), check if we can form that bit using available powers of 2.
  3. 3Step 3: If a required power is missing, perform operations to create it from larger powers, counting each operation.
  4. 4Step 4: If we can form the target sum using available powers, return the total operations; otherwise, return -1.
solution.py22 lines
1# Full working Python code
2from collections import Counter
3
4def min_operations_optimal(nums, target):
5    count = Counter(nums)
6    operations = 0
7    for i in range(32):  # Powers of 2 up to 2^31
8        if (target >> i) & 1:
9            if count[1 << i] > 0:
10                count[1 << i] -= 1
11            else:
12                # Need to create this power
13                while (1 << i) > 1:
14                    if count[1 << (i + 1)] > 0:
15                        operations += 1
16                        count[1 << (i + 1)] -= 1
17                        count[1 << i] += 2
18                        break
19                    i += 1
20                else:
21                    return -1
22    return operations

Complexity note: This complexity is efficient because we only traverse the list of numbers and the bits of the target, leading to a linear time complexity relative to the size of the input.

  • 1Understanding how to break down larger powers of 2 is crucial for forming the target sum efficiently.
  • 2Using a greedy approach allows us to minimize operations by always trying to use the largest available power of 2.

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