Minimum Operations to Form Subsequence With Target Sum - Problem

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.
  • Remove nums[i] from the array.
  • Add two occurrences of nums[i] / 2 to the end of nums.

Return the minimum number of operations you need to perform so that nums contains a subsequence whose elements sum to target. If it is impossible to obtain such a subsequence, return -1.

A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.

Input & Output

Example 1 — Basic Split Required
$ Input: nums = [1,1,4], target = 3
Output: 1
💡 Note: We have two 1s and one 4. To form target 3, we need a 2. We can split 4 → [2,2] in 1 operation, then use 1+2=3.
Example 2 — No Operations Needed
$ Input: nums = [1,2,8], target = 3
Output: 0
💡 Note: We already have 1 and 2 in the array. We can directly form 1+2=3 without any operations.
Example 3 — Impossible Case
$ Input: nums = [1,2], target = 4
Output: -1
💡 Note: Total sum is 1+2=3, which is less than target 4. It's impossible to reach target 4.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 106
  • nums[i] is a power of 2
  • 1 ≤ target ≤ 106

Visualization

Tap to expand
Minimum Operations to Form Target SumInput: nums=[1,1,4]Target: 3Powers of 2 availableOperation: Split 4 → [2,2]New array: [1,1,2,2]1 operation performedResult: 1 operationSubsequence: [1,2]Sum: 1+2 = 3 ✓Key Strategy: Greedy Bit Manipulation1. Process target bit by bit (3 = 011₂)2. Use available denominations or split larger ones3. Count operations needed for splitsTime: O(log target) | Space: O(log max(nums))
Understanding the Visualization
1
Input Analysis
Array of powers of 2 and target sum to achieve
2
Split Strategy
Split larger denominations into smaller ones when needed
3
Form Target
Use greedy approach to select subsequence summing to target
Key Takeaway
🎯 Key Insight: Use greedy bit manipulation to process target bit-by-bit and minimize splits
Asked in
Google 15 Meta 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
428 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