Construct Target Array With Multiple Sums - Problem

You are given an array target of n integers. From a starting array arr consisting of n 1's, you may perform the following procedure:

  • Let x be the sum of all elements currently in your array.
  • Choose index i, such that 0 <= i < n and set the value of arr at index i to x.

You may repeat this procedure as many times as needed.

Return true if it is possible to construct the target array from arr, otherwise, return false.

Input & Output

Example 1 — Basic Possible Case
$ Input: target = [9,3,5]
Output: true
💡 Note: Starting from [1,1,1]: Replace index 0 with sum=3 → [3,1,1], then replace index 2 with sum=5 → [3,1,5], finally replace index 0 with sum=9 → [9,3,5]. Working backwards confirms this is possible.
Example 2 — Impossible Case
$ Input: target = [1,1,1,2]
Output: false
💡 Note: The sum is 5. For 2 to be created, the previous sum must have been 2, but that would require other elements to sum to 0, which is impossible since all elements must be positive.
Example 3 — Single Element
$ Input: target = [8]
Output: true
💡 Note: Single element case: start with [1], replace with 1 → [1], replace with 1 → [1], ..., eventually we can build up to any positive integer.

Constraints

  • 1 ≤ target.length ≤ 5 × 104
  • 1 ≤ target[i] ≤ 109

Visualization

Tap to expand
Construct Target Array With Multiple Sums INPUT Target Array 9 index 0 3 index 1 5 index 2 Starting Array (all 1's) 1 1 1 Goal: Transform [1,1,1] into [9,3,5] using sum replacement n = 3, sum = 17 ALGORITHM STEPS 1 Work Backwards Use max-heap, start from target, reduce to [1,1,1] 2 Extract Maximum Pop max=9, rest_sum=8 new_val = 9 - 8 = 1 3 Repeat Process [1,3,5] max=5, rest=4 5-4=1 --> [1,3,1] 4 Continue Until Done [1,3,1] max=3, rest=2 3-2=1 --> [1,1,1] Backward Trace: [9,3,5] --> [1,3,5] [1,3,5] --> [1,3,1] [1,3,1] --> [1,1,1] OK FINAL RESULT OK true Output: true Transformation Valid! Verification Path: [1,1,1] sum=3 [3,1,1] sum=5 [3,5,1] sum=9 [3,5,9] = [9,3,5] Key Insight: Work backwards from target using a max-heap. The largest element was created last, so we can reverse the operation: new_value = max - rest_sum. Use modulo for optimization when max is much larger than rest_sum. If we reach [1,1,...,1], return true. Time: O(n log n log m) TutorialsPoint - Construct Target Array With Multiple Sums | Optimal Solution
Asked in
Google 15 Amazon 12 Facebook 8
32.0K Views
Medium Frequency
~25 min Avg. Time
892 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