Loading the journal
Loading the journal
Invariant (Sum Preserved)
Problem
You are given two integer arrays source and target.
In one operation, you may choose two distinct indices i and j in source, along with any integer delta. Then update:
source[i] = source[i] + source[j] - delta
source[j] = delta
Return true if it is possible to make source equal to target after any number of operations (including zero), otherwise false.
Input: source = [1,2,3], target = [0,2,4]
Output: true
Explanation: i = 0, j = 2, delta = 4 → [0, 2, 4]
Input: source = [-5,-5], target = [-15,5]
Output: true
Input: source = [1,2,1], target = [0,2,5]
Output: false
2 ≤ source.length == target.length ≤ 10^5
-10^9 ≤ source[i], target[i] ≤ 10^9
Look at what happens to :
source[i] + source[j]before: source[i] + source[j]
after: (source[i] + source[j] - delta) + delta = source[i] + source[j]
→ Every operation preserves the total sum. So sum(source) == sum(target) is necessary.
It is also sufficient (n ≥ 2): use the last index as a "sink".
For every j < n-1, apply the operation with i = n-1 and delta = target[j].
Each source[j] becomes exactly target[j], and the sink absorbs the difference —
since the sum never changes, the sink ends up equal to target[n-1].
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code