#1354
Construct Target Array With Multiple Sums
HardArrayHeap (Priority Queue)Heap (Priority Queue)Array
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Instead of building the target array from the starting array, we can reverse the process. By continuously subtracting the largest element from the sum of the rest, we can determine if we can reach the starting state of all 1s.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total sum of the target array.
- 2Step 2: While the largest element is greater than 1, subtract the largest element by the sum of the rest of the elements.
- 3Step 3: Update the largest element and repeat until all elements are 1 or the largest element is less than or equal to the sum of the rest.
solution.py14 lines
1# Full working Python code
2class Solution:
3 def isPossible(self, target):
4 total = sum(target)
5 while True:
6 max_val = max(target)
7 if max_val == 1:
8 return True
9 total -= max_val
10 if total <= 0 or total >= max_val:
11 return False
12 target[target.index(max_val)] = max_val % total
13 total += target[target.index(max_val)]
14ℹ
Complexity note: The time complexity is O(n log n) because we need to find the maximum element in the array repeatedly, which takes O(n) time, and this is done in a loop until we reach the base case.
- 1The largest element must be formed last, as it is the sum of the rest.
- 2The process can be reversed to check if we can reach the starting state.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.