You're given a list of triplets and a target triplet. You may repeatedly merge any two triplets by taking the elementwise maximum of each. Return true if it's possible to end up with a triplet exactly equal to target.
Merging only ever takes the max per coordinate, so it can never lower a value — only raise it toward or past the target. Any triplet with a coordinate exceeding the target's would overshoot, so it must be discarded entirely.
For each of the three positions, at least one "safe" (non-overshooting) triplet must hit the target exactly at that position, or the elementwise max can never reach it there.
Track which of the three coordinates have been matched exactly by at least one safe triplet.
Step-by-Step Analysis
Initialize an empty set good to track which coordinates (0, 1, 2) have been matched exactly.
For each triplet t: if any t[i] > target[i], skip it — it would overshoot.
Otherwise, for each coordinate i where t[i] == target[i], add i to good.
Return True if good contains all three coordinates, else False.
Complexity
Time: O(n) — Space: O(1)
Code
def mergeTriplets(triplets: list[list[int]], target: list[int]) -> bool:
good = set()
for t in triplets:
if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:
continue
for i in range(3):
if t[i] == target[i]:
good.add(i)
return len(good) == 3
Code Explanation
How the solution above works, piece by piece.
Merging takes the element-wise maximum, so values can only grow. A triplet with any value above the target would push that position past the target forever: never use it.
Every other triplet is safe to merge; it can't overshoot.
Record which positions a safe triplet matches exactly in good.
If each of the 3 positions is matched by some safe triplet, merging all safe triplets produces the target exactly.
One pass, O(n) time, O(1) space.
Visual Walkthrough
Running it on triplets = [[2, 5, 3], [1, 8, 4], [1, 7, 5]], target = [2, 7, 5]:
[1, 8, 4] is skipped because 8 > 7. The other two are safe: [2, 5, 3] supplies the 2 and [1, 7, 5] supplies the 7 and 5. Merging them gives [2, 7, 5].