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 Subsequence With Target Sum INPUT nums array (powers of 2): 1 2^0 1 2^0 4 2^2 Target Sum: 3 Binary: 3 = 11 (bits 0,1) Current sum: 1+1+4 = 6 Need sum = 3 Bit 0: count=2, Bit 2: count=1 Bit 1: count=0 (missing!) ALGORITHM STEPS 1 Count bits in nums Track each power of 2 2 Process target bits Check bit 0: need 1, have 2 3 Check bit 1: need 1 Have 0, must split larger 4 Split 4 into 2+2 1 operation needed Split Operation: 4 --> 2 2 New array: [1,1,2,2] Subsequence: 1+2 = 3 [OK] Operations: 1 FINAL RESULT After 1 operation: 1 1 2 2 Valid Subsequence: 1 + 2 = 3 (target) Output: 1 [OK] Minimum operations to form target sum Key Insight: Use greedy bit manipulation: process bits from LSB to MSB. If a bit is needed but unavailable, split the next available larger power of 2. Each split costs 1 operation and creates 2 smaller values. TutorialsPoint - Minimum Operations to Form Subsequence With Target Sum | Greedy Bit Manipulation
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