Leetcode #2835: Minimum Operations to Form Subsequence With Target Sum
In this guide, we solve Leetcode #2835 Minimum Operations to Form Subsequence With Target Sum in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed array nums consisting of non-negative powers of 2, and an integer target. In one operation, you must apply the following changes to the array: Choose any element of the array nums[i] such that nums[i] > 1.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Greedy, Bit Manipulation, Array
Intuition
A locally optimal choice leads to a globally optimal result for this structure.
That means we can commit to decisions as we scan without backtracking.
Approach
Sort or preprocess if needed, then repeatedly take the best available local choice.
Maintain the minimal state necessary to validate the greedy decision.
Steps:
- Sort or preprocess as needed.
- Iterate and pick the best local option.
- Track the current solution.
Example
Input: nums = [1,2,8], target = 7
Output: 1
Explanation: In the first operation, we choose element nums[2]. The array becomes equal to nums = [1,2,4,4].
At this stage, nums contains the subsequence [1,2,4] which sums up to 7.
It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7.
Python Solution
class Solution:
def minOperations(self, nums: List[int], target: int) -> int:
s = sum(nums)
if s < target:
return -1
cnt = [0] * 32
for x in nums:
for i in range(32):
if x >> i & 1:
cnt[i] += 1
i = j = 0
ans = 0
while 1:
while i < 32 and (target >> i & 1) == 0:
i += 1
if i == 32:
break
while j < i:
cnt[j + 1] += cnt[j] // 2
cnt[j] %= 2
j += 1
while cnt[j] == 0:
cnt[j] = 1
j += 1
ans += j - i
cnt[j] -= 1
j = i
i += 1
return ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.