Merge Triplets to Form Target Triplet

MediumGreedyLeetCode 1899 ↗World 7-21
0:00 / 0:00

Can some triplets merge, by taking maxes, into a target? Skip any triplet that overshoots, then check the safe ones still reach every value.

▼

The problem

You get a list of triplets and a target triplet. Merging two triplets a and b gives [max(a0, b0), max(a1, b1), max(a2, b2)]. You may merge any triplets any number of times. Return whether the target can appear as one of the triplets.

Example (LeetCode's, the one animated): triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] → true (merge the first and the last).

TRY IT ON LEETCODE ▶

The solution

def mergeTriplets(triplets, target):
    good = set()
    for t in triplets:
        if any(t[i] > target[i] for i in range(3)):
            continue  # poison: skip it
        for i in range(3):
            if t[i] == target[i]:
                good.add(i)
    return len(good) == 3

Transcript

Merge Triplets to Form Target Triplet. You get a list of triplets, three numbers each, and one target. Merging two triplets keeps the larger number in every position. Merge as often as you like: can you build the target exactly?

Take two five three, one eight four, and one seven five, with the target two seven five. Merge the first and the last: two beats one, seven beats five, five beats three. Two, seven, five. That's the target: true.

The naive way tries every group of triplets and merges each one. With n triplets, that's two to the n groups. Thirty triplets already make over a billion.

Picture each triplet as a paint tin with three levels: red, yellow and blue. Pouring a tin into the mixer is a merge: each gauge rises to the higher level. The target is a line on each gauge, and paint never comes back out.

That gives one rule. A tin with any level above its line would overshoot for good. It's poison: skip it. Every other tin is safe. Pour them all, and no gauge can pass its line. So the answer is true exactly when every line is hit by some safe tin.

In code, keep a set of good positions. For each triplet, if any number is bigger than the target's, skip it. Otherwise, mark each position where it equals the target. Return whether all three are marked.

Back to the example. Two five three is safe, and hits the red line. One eight four has an eight, above seven: poison, into the bin. One seven five is safe, and hits seven and five. All three lines are marked: true. Now raise the blue line to six. Nothing safe reaches six, so the answer is false.

Each triplet is checked once, so the time is order n. The set holds at most three marks, so the space is order one.

Skip the poison, pour the rest, and check every line. That's Merge Triplets to Form Target Triplet.