Merge Triplets to Form Target Triplet (LeetCode 1899): Solution and Explanation

Medium
Array
Greedy

You have a list of triplets and a target triplet. Merging two triplets replaces one of them with the element-wise maximum of both, and you may merge as many times as you like. Decide whether some sequence of merges can produce a triplet exactly equal to the target.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force idea is to try merges in different orders and see whether any sequence lands on the target. That explodes quickly, and it misses the real structure of the operation. A merge takes the maximum in each position, so values can only grow. Once a position goes above the target value, nothing can bring it back down, which means any triplet that touches it is poison.

That gives the first observation: a triplet with any coordinate larger than the matching target coordinate can never be part of a successful merge. If you merged it in, the result would exceed the target in that position forever. So you throw those triplets away and only consider the safe ones, the triplets where every value is at most the target value in the same slot.

The second observation is that merging all the safe triplets together is never harmful. Each position of the merged result is the maximum over safe triplets, and since every safe value is at most the target, the result is at most the target everywhere. The result equals the target exactly when, for each of the three positions, at least one safe triplet hits that target value. So the whole question collapses to checking which positions are covered.

The reference code tracks this with a set called good. For each safe triplet it adds every index where the triplet's value equals the target's value. If the set ends up holding all three indices, the answer is true. There is no need to actually perform any merge.

Approach: Greedy filter with coverage set

  1. Create an empty set good that will record which target positions have been matched.
  2. Loop over every triplet t in triplets.
  3. If t[0] > target[0], t[1] > target[1] or t[2] > target[2], skip the triplet, because merging it would overshoot the target in that position.
  4. Otherwise, for each index i with value v in the triplet, add i to good when v == target[i].
  5. After the loop, return whether len(good) == 3, meaning all three positions can be reached by merging the safe triplets.

Step-by-step example

triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
  1. Start with good empty.
  2. Triplet [2,5,3]: every value is within the target (2 ≤ 2, 5 ≤ 7, 3 ≤ 5), so it is safe. Position 0 matches (2 equals 2), so good becomes {0}.
  3. Triplet [1,8,4]: the middle value 8 is larger than 7, so this triplet is skipped entirely, even though it would not match anything anyway.
  4. Triplet [1,7,5]: it is safe. Position 1 matches (7 equals 7) and position 2 matches (5 equals 5), so good becomes {0, 1, 2}.
  5. The set has three elements, so the function returns true. Merging [2,5,3] with [1,7,5] gives [2,7,5], which is the target.

Code: Python, Java, C++

1class Solution:
2    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
3        good = set()
4        
5        for t in triplets:
6            if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:
7                continue
8            
9            for i, v in enumerate(t):
10                if v == target[i]:
11                    good.add(i)
12                    
13        return len(good) == 3

Time and space complexity

Time

O(n)

Each of the n triplets is examined once, and the work per triplet is a constant three comparisons plus at most three set insertions.

Space

O(1)

The set good can never hold more than three indices, so the extra memory does not grow with the input.

Other approaches

Running merged maximum (time O(n), space O(1))

Instead of a set, keep a running triplet initialized to [0,0,0] and merge every safe triplet into it with element-wise maximum. At the end, compare it to the target. It is the same idea expressed by literally simulating the merge of all safe triplets, and some people find it easier to justify in an interview.

Brute force over subsets (time O(2^n × n), space O(n))

Try every subset of triplets, merge each one and check against the target. It is correct but exponential, and only useful as a mental starting point before you notice that merging all safe triplets is always best.

Common mistakes

  • Marking positions from a triplet before checking whether it is safe. A triplet like [2,8,5] with target [2,7,5] matches two positions but must be ignored, because merging it pushes the middle value to 8.
  • Requiring a single triplet to match all three positions. Different safe triplets can each contribute a different coordinate, which is the whole point of merging.
  • Using a strict comparison in the filter. Values equal to the target are exactly what you want, so skip only when a value is strictly greater.
  • Counting matches with a plain integer instead of a set, which double counts when two safe triplets match the same position and can report three matches with a position still missing.

Frequently asked questions

Why can we ignore any triplet with a value above the target?

Merging takes the maximum in each position, so values never decrease. If a triplet has a coordinate above the target, every merge that includes it keeps that coordinate above the target, so it can never be part of a valid answer.

Why is merging all safe triplets always optimal?

Every safe triplet is at most the target in every position, so their combined maximum is also at most the target. Adding more safe triplets can only raise positions toward the target, never past it, so including all of them can only help.

Is Merge Triplets a greedy problem?

Yes. The greedy choice is to take every triplet that does not overshoot. Once you see that safe triplets never hurt, the problem becomes a single linear scan with no backtracking.

What is the time and space complexity?

The scan is O(n) time because each triplet is checked in constant time. Extra space is O(1), since the set of matched positions holds at most three entries.