Merge Triplets to Form Target Triplet
Difficulty: Medium · Pattern: Greedy · LeetCode #1899
Merging two triplets takes the element-wise max. Can you choose some triplets whose merge equals target exactly?
Examples
text
triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] → true (merge #1 and #3)
triplets = [[3,4,5],[4,5,6]], target = [3,2,5] → false
triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] → trueHints
- A triplet with any coordinate greater than the target's can never be used, because max never decreases.
- Every other triplet is safe to merge. It can only help. Do the safe ones together reach each target value?
Approach
Filter out the triplets that exceed target in any coordinate. Among the rest, check that for each coordinate k, some triplet has t[k] == target[k]. Merging all the safe triplets gives exactly target in that case, since every coordinate is at most the target value and some triplet hits it.
O(n) time, O(1) space. The key insight is that using more safe triplets never hurts under a max operation.
Complexity
Time: O(n). Space: O(1).
Python solution
def mergeTriplets(triplets, target):
hit = [False, False, False]
for t in triplets:
if all(t[k] <= target[k] for k in range(3)):
for k in range(3):
if t[k] == target[k]:
hit[k] = True
return all(hit)JavaScript solution
function mergeTriplets(triplets, target) {
const hit = [false, false, false];
for (const t of triplets) {
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) continue;
for (let k = 0; k < 3; k++) if (t[k] === target[k]) hit[k] = true;
}
return hit.every(Boolean);
}