Magicsheet logo

Construct Target Array With Multiple Sums

Hard
100%
Updated 6/1/2025

Asked by 1 Company

Construct Target Array With Multiple Sums

What is this problem about?

The Construct Target Array With Multiple Sums interview question is a "reverse" simulation problem. You start with an array of all 1s. In each step, you calculate the sum of the current array and replace one element with that sum. You are given a target array and must determine if it can be reached from the starting state of 1s.

Why is this asked in interviews?

This Construct Target Array With Multiple Sums coding problem is a favorite at high-tier companies like Quora. It tests whether a candidate can think backward. Trying to simulate forward is impossible because of the infinite branching factor, but simulating backward from the target to the 1s is deterministic.

Algorithmic pattern used

This utilizes the Array, Heap (Priority Queue) interview pattern.

  1. The largest number in the target array must have been the "sum" from the previous step.
  2. Total Sum S of the current array is known.
  3. The previous value of the largest element L was L - (S - L).
  4. Use a Max-Heap to efficiently retrieve and update the largest element.
  5. Optimization: Instead of subtracting (S-L) repeatedly (which is slow for cases like [1, 10^9]), use the modulo operator to jump multiple steps back.

Example explanation

Target: [9, 3, 5]

  1. Sum = 17. Max = 9.
  2. Remaining Sum = 17 - 9 = 8.
  3. Previous value of 9 was 9 % 8 = 1. (Note: if 9 % 8 == 0, use 8).
  4. New array: [1, 3, 5]. Sum = 9. Max = 5.
  5. Remaining Sum = 9 - 5 = 4.
  6. Previous value of 5 was 5 % 4 = 1.
  7. New array: [1, 3, 1]. Sum = 5. Max = 3.
  8. Remaining Sum = 5 - 3 = 2.
  9. Previous value of 3 was 3 % 2 = 1.
  10. New array: [1, 1, 1]. Success!

Common mistakes candidates make

  • Forward simulation: Trying to build up from 1s, which leads to exponential time complexity.
  • Handling 0 or negative results: Not checking if the "previous value" calculation becomes less than 1.
  • Modulo edge cases: Forgetting to handle the case where the remaining sum is 1 (which always allows reaching the target) or when the modulo result is 0.

Interview preparation tip

"Reverse simulation" is a powerful paradigm. If a problem seems to have too many choices at the start but only one choice at the "end," try working backward from the output to the input.

Similar Questions