← DSA
MEDIUM

Merge Triplets to Form Target Triplet

PracticeNeetCode ↗LeetCode ↗

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.

Example

Input triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output true

Key Pointers

Step-by-Step Analysis

  1. Initialize an empty set good to track which coordinates (0, 1, 2) have been matched exactly.
  2. For each triplet t: if any t[i] > target[i], skip it — it would overshoot.
  3. Otherwise, for each coordinate i where t[i] == target[i], add i to good.
  4. 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.

  1. 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.
  2. Every other triplet is safe to merge; it can't overshoot.
  3. Record which positions a safe triplet matches exactly in good.
  4. If each of the 3 positions is matched by some safe triplet, merging all safe triplets produces the target exactly.
  5. 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]:

trace253[2, 5, 3]usable; matches position(s) 0184[1, 8, 4]skip: 8 > 7 would overshoot175[1, 7, 5]usable; matches position(s) 1, 2275targetpositions 0, 1, 2 all covered → True
[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].
exact matchtoo bigcovered

Video Explanation

NeetCode — Greedy, LeetCode 1899