15% off all plans & roadmaps Use code

See plans

Merge Triplets to Form Target Triplet

Updated

TL;DR: Throw away every triplet that has a value above the target in any position. Then check that the remaining triplets hit each of the three target values exactly. A single pass with three flags does both.

Problem

You are given a list triplets, where each entry is an array of three integers. You are also given target, an array of three integers. Treat the three positions of every triplet as separate coordinates.

You may pick any collection of triplets, using each at most once, and merge them. A merge takes the largest value at each coordinate across the picked triplets. For example, the merged first coordinate is the largest first coordinate among them. Return true if some selection merges to exactly target, and false otherwise.

Example 1

Input: triplets = [[2,4,1],[1,3,5],[2,3,4]], target = [2,4,5]
Output: true
Explanation: The first two triplets are each no larger than the target in every coordinate. Their coordinate-wise maximum is [2,4,5], which equals the target.

Example 2

Input: triplets = [[4,1,2],[2,5,2],[3,2,6]], target = [3,5,2]
Output: false
Explanation: The first triplet exceeds the target in its first coordinate, and the third exceeds it in its third coordinate. The remaining triplet cannot supply the target's first coordinate.

Example 3

Input: triplets = [[1,2,3],[2,1,2],[1,2,2]], target = [2,2,3]
Output: true
Explanation: The first triplet supplies the third coordinate and the second supplies the first. Together their maximum is [2,2,3].

Constraints

  • 1 <= triplets.length <= 10^5
  • triplets[i].length == 3
  • 1 <= triplets[i][j] <= 10^3
  • target.length == 3
  • 1 <= target[j] <= 10^3

Constraints that matter

  • triplets.length up to 10^5 rules out trying every subset, since 2^n subsets is far beyond any time limit. You need a near-linear scan.
  • Each triplet has exactly three values, so any per-triplet work is O(1). That makes one pass over the input enough.
  • All values are at least 1, so a running maximum can start at 0 and an empty selection can never equal the target.
  • Values stay within 10^3, so there are no overflow worries in any language and plain int is safe.

View on LeetCode

Hints

Hint 1

This is a greedy problem with a filtering step.

Hint 2

Treat the problem literally.

Solution

Intuition

This is a greedy problem with a filtering step. A merge takes a maximum, and a maximum never goes down when you add more triplets. So a triplet with any value above the target can never be part of a valid answer. You can discard it without looking at the others.

Picture three checkboxes on a clipboard, one per coordinate. The three flags are those boxes, and each acceptable triplet ticks every box where it matches the target exactly.

After that filter, every surviving triplet is at most the target in all three positions. Merging any group of survivors therefore stays at or below the target. The only question left is whether the merge can reach the target in each position.

To reach target[i] exactly, some survivor must hold exactly that value at position i. Different positions may be served by different triplets, because the maximum is taken per coordinate. So the answer is true when each of the three positions has at least one survivor that matches it.

Greedy fits because each triplet can be judged alone against a fixed target. You never compare triplets with each other, and no choice blocks a later choice. Using every survivor is always safe, which removes the need to search over subsets.

Watch the pattern animation

Worked example

Input: triplets = [[1,1,1]], target = [1,1,1]
Output: true
Explanation: There is one triplet and it equals the target. It never exceeds the target, and it supplies all three target values, so merging it alone gives [1,1,1].

Approach 1: Brute force: try every subset

Treat the problem literally. For each triplet you either include it in the merge or leave it out. Walk through all of these choices, compute the coordinate-wise maximum for each, and compare it with target.

This is correct but exponential. With n triplets there are 2^n selections, so it only works for tiny inputs.

Steps

  1. Define a recursive function over the index i and the running maximums a, b, c.
  2. At i equal to n, return whether (a, b, c) equals the target.
  3. Otherwise try skipping triplet i and keep a, b, c as they are.
  4. Also try including triplet i, raising each running maximum with max.
  5. Return true if either branch returns true.
  6. Start the recursion at index 0 with maximums (0, 0, 0).

Dry run

Example: triplets = [[1,1,1]], target = [1,1,1].

  • Start at index 0 with maximums (0,0,0).
  • Skip branch: index 1 is the end, and (0,0,0) is not (1,1,1), so false.
  • Include branch: maximums become (1,1,1). Index 1 is the end and (1,1,1) equals the target, so true.
  • The first branch returned false and the second true, so the result is true.

Complexity

TimeO(2^n)
SpaceO(n)

Here n is the number of triplets. Each triplet creates a two-way branch, so the recursion tree has 2^n leaves, and each node does O(1) work with three coordinates. The recursion depth is n, so the call stack uses O(n) space. At n = 10^5 this is impossible, so the approach only serves as a correctness baseline.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
        n = len(triplets)

        def pick(i: int, a: int, b: int, c: int) -> bool:
            if i == n:
                return a == target[0] and b == target[1] and c == target[2]
            t = triplets[i]
            # skip triplet i, or take it and raise the running maximums
            return pick(i + 1, a, b, c) or pick(i + 1, max(a, t[0]), max(b, t[1]), max(c, t[2]))

        return pick(0, 0, 0, 0)

Approach 2: Filter, then merge every survivor

What's slow: the brute force explores selections that include an oversized triplet. Those can never succeed, yet the recursion still expands them. It also tries many subsets whose merge is only a part of what a bigger subset would give.

The insight that fixes it: a triplet is either safe or unusable, and the target alone decides which. Keep every safe triplet, then merge all of them at once. Adding more safe triplets only raises the maximums toward the target and never past it. So if any subset of safe triplets reaches the target, the merge of all safe triplets does too.

Steps

  1. Create an empty list valid.
  2. For each triplet, keep it only if all three values are at most the matching target values.
  3. Start a merged triplet at (0, 0, 0).
  4. For each triplet in valid, raise each merged coordinate with max.
  5. Compare the merged triplet with the target in all three positions.
  6. Return the result of that comparison.

Dry run

Example: triplets = [[1,1,1]], target = [1,1,1].

  • Filter: 1 <= 1 in all three positions, so [1,1,1] goes into valid.
  • Merge: start at (0,0,0). After [1,1,1] the merge is (1,1,1).
  • Compare: (1,1,1) equals (1,1,1), so the result is true.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of triplets. The filter pass looks at each triplet once with three comparisons, and the merge pass looks at each survivor once with three max operations, so the total work is about 6n steps. In the worst case the valid list holds every triplet, which costs O(n) extra space.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
        # keep only triplets that never exceed the target
        valid = [t for t in triplets
                 if t[0] <= target[0] and t[1] <= target[1] and t[2] <= target[2]]
        merged = [0, 0, 0]
        for t in valid:
            for i in range(3):
                merged[i] = max(merged[i], t[i])
        return merged == target
Sorting Based pattern infographic for Merge Triplets to Form Target Triplet

Solution pattern

Sorting Based

Part of Greedy Patterns

Approach 3: One-pass greedy with three flagsOptimalSorting Based

What's slow: the previous approach builds a second list and walks it again. The list exists only to be merged afterward, and the merge does not need it.

The insight that fixes it: after the filter, the merge reaches the target exactly when each position has at least one survivor with the exact target value. That is three yes or no facts. Keep three booleans and update them as you scan. Each flag only goes from false to true, so no earlier triplet ever needs a second look.

Steps

  1. Create three flags, all false, one per coordinate.
  2. Read the next triplet.
  3. If any of its values is above the matching target value, skip it.
  4. Otherwise, for each coordinate where the triplet equals the target, set that flag to true.
  5. Repeat until all triplets are read.
  6. Return true only if all three flags are true.

Dry run

Example: triplets = [[1,1,1]], target = [1,1,1]. The table tracks the three flags.

StepActionExceeds target?flag0flag1flag2
0startnofalsefalsefalse
1read [1,1,1], check 1 > 1 for each positionnofalsefalsefalse
2position 0: 1 == 1notruefalsefalse
3position 1: 1 == 1notruetruefalse
4position 2: 1 == 1notruetruetrue
5no triplets left, return flag0 and flag1 and flag2notruetruetrue

All three flags are true, so the result is true.

On Example 1 ([[2,4,1],[1,3,5],[2,3,4]], target [2,4,5]) the flags go from (F,F,F) to (T,T,F) after [2,4,1], then to (T,T,T) after [1,3,5]. The third triplet changes nothing.

Complexity

TimeO(n)
SpaceO(1)

Here n is the number of triplets. The loop visits each triplet once and does a fixed number of comparisons, three for the filter and three for the matches, so the total work is proportional to n. The only extra storage is three booleans, which does not grow with n.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
        matched = [False, False, False]
        for t in triplets:
            # a triplet above the target anywhere can never be used
            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]:
                    matched[i] = True
        return all(matched)

Common mistakes

  • Updating matched[i] before the exceed check. A triplet like [2,4,6] against target [2,4,5] matches two positions but is unusable. Run the filter first and continue before any flag changes.
  • Requiring one triplet to match all three positions, for example if t == target. Different triplets can supply different coordinates. Track three separate flags instead.
  • Dropping a triplet only when all coordinates exceed the target. One oversized coordinate is enough to ruin the merge, so use or between the three comparisons, not and.
  • Comparing with >= or == in the filter, such as t[i] != target[i]. Smaller values are harmless because the maximum ignores them. Reject only on t[i] > target[i].
  • Starting the running maximum at the first triplet and forgetting to filter, so an oversized triplet leaks into merged. Filter first, and start the maximum at 0 since all values are at least 1.
  • Sorting the triplets first because the pattern label says sorting. Sorting adds O(n log n) and changes nothing, since each triplet is judged only against the fixed target.

Edge cases

  • One triplet equal to the target, such as [[1,1,1]] with [1,1,1]: return true.
  • One triplet that is smaller than the target in some position, such as [[1,1,1]] with [2,2,2]: return false, because nothing supplies the exact values.
  • A triplet that matches two positions but exceeds in the third, such as [2,4,6] with target [2,4,5]: it is ignored, and the answer depends on the other triplets.
  • Every triplet exceeds the target somewhere: no flag is ever set, so return false.
  • The target values come from three different triplets, as in Example 3: return true, since flags are independent.
  • Maximum size, 10^5 triplets: the one-pass scan runs in linear time, while the brute force cannot finish.

Follow-ups interviewers ask

Why is it safe to merge every valid triplet instead of choosing a subset?
Each valid triplet is at most the target in all coordinates, so merging more of them never pushes a coordinate past the target. Extra valid triplets can only raise coordinates toward the target. If some subset reaches the target, the full set of valid triplets reaches it too.
What if each triplet had k coordinates instead of three?
The same idea holds. Skip any triplet that exceeds the target at some coordinate, and keep k flags, one per coordinate. The time becomes O(n * k) and the space O(k), or O(1) extra if you reuse a bitmask when k is small.
What if the triplets arrive as a stream and you cannot store them?
The one-pass solution already works on a stream. It keeps only three booleans and never revisits a triplet. You can also stop early and return true once all three flags are set.

Merge Triplets to Form Target Triplet FAQ

What is the time complexity of Merge Triplets to Form Target Triplet?

The optimal solution runs in O(n) time, where n is the number of triplets. Each triplet takes a fixed number of comparisons, and the solution uses O(1) extra space. The subset brute force costs O(2^n).

Why use a greedy approach for Merge Triplets to Form Target Triplet?

A merge takes maximums, which never decrease, so any triplet above the target can be rejected on its own. The rest are all safe to use together. That removes any need to search over subsets, and a single scan decides the answer.

Do all three target values have to come from the same triplet?

No. The merge takes the maximum per coordinate, so one triplet can supply the first value, another the second, and another the third. Example 3 works this way: [1,2,3] supplies the third value and [2,1,2] supplies the first.

Can Merge Triplets to Form Target Triplet be solved in O(1) extra space?

Yes. The one-pass solution keeps only three boolean flags, which is constant space whatever the input size. The filter-then-merge version uses O(n) space only because it stores the valid list.

Does this problem need sorting even though it is tagged as sorting based?

No. Each triplet is compared only with the fixed target, so order does not matter. A linear scan is enough, and sorting would add O(n log n) with no benefit.

How do I write Merge Triplets to Form Target Triplet in Python or Java?

Use three flags, skip any triplet with a value above the target, and set a flag when a coordinate equals the target. The page above has the same algorithm in Python, Java, C++, JavaScript, Go and C#.

Asked at

See which companies ask this — Pro

Practise it