15% off all plans & roadmaps Use code
See plansMerge Triplets to Form Target Triplet
- LeetCode 1899
- Medium
- Greedy Patterns
- Sorting Based
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^5triplets[i].length == 31 <= triplets[i][j] <= 10^3target.length == 31 <= 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.
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.
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
- Define a recursive function over the index i and the running maximums a, b, c.
- At i equal to n, return whether (a, b, c) equals the target.
- Otherwise try skipping triplet i and keep a, b, c as they are.
- Also try including triplet i, raising each running maximum with max.
- Return true if either branch returns true.
- 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
| Time | O(2^n) |
|---|---|
| Space | O(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)JavaTested in our runner
import java.util.*;
class Solution {
public boolean mergeTriplets(int[][] triplets, int[] target) {
return pick(triplets, target, 0, 0, 0, 0);
}
private boolean pick(int[][] triplets, int[] target, int i, int a, int b, int c) {
if (i == triplets.length) {
return a == target[0] && b == target[1] && c == target[2];
}
int[] t = triplets[i];
// skip triplet i, or take it and raise the running maximums
return pick(triplets, target, i + 1, a, b, c)
|| pick(triplets, target, i + 1, Math.max(a, t[0]), Math.max(b, t[1]), Math.max(c, t[2]));
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
return pick(triplets, target, 0, 0, 0, 0);
}
private:
bool pick(vector<vector<int>>& triplets, vector<int>& target, int i, int a, int b, int c) {
if (i == (int)triplets.size()) {
return a == target[0] && b == target[1] && c == target[2];
}
const vector<int>& t = triplets[i];
// skip triplet i, or take it and raise the running maximums
return pick(triplets, target, i + 1, a, b, c)
|| pick(triplets, target, i + 1, max(a, t[0]), max(b, t[1]), max(c, t[2]));
}
};JavaScriptTested in our runner
/**
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target) {
const n = triplets.length;
const pick = (i, a, b, c) => {
if (i === n) {
return a === target[0] && b === target[1] && c === target[2];
}
const t = triplets[i];
// skip triplet i, or take it and raise the running maximums
return pick(i + 1, a, b, c) ||
pick(i + 1, Math.max(a, t[0]), Math.max(b, t[1]), Math.max(c, t[2]));
};
return pick(0, 0, 0, 0);
};GoTested in our runner
func mergeTriplets(triplets [][]int, target []int) bool {
n := len(triplets)
max := func(x, y int) int {
if x > y {
return x
}
return y
}
var pick func(i, a, b, c int) bool
pick = func(i, a, b, c int) bool {
if i == n {
return a == target[0] && b == target[1] && c == target[2]
}
t := triplets[i]
// skip triplet i, or take it and raise the running maximums
return pick(i+1, a, b, c) || pick(i+1, max(a, t[0]), max(b, t[1]), max(c, t[2]))
}
return pick(0, 0, 0, 0)
}C#Tested in our runner
public class Solution {
public bool mergeTriplets(int[][] triplets, int[] target) {
return Pick(triplets, target, 0, 0, 0, 0);
}
private bool Pick(int[][] triplets, int[] target, int i, int a, int b, int c) {
if (i == triplets.Length) {
return a == target[0] && b == target[1] && c == target[2];
}
int[] t = triplets[i];
// skip triplet i, or take it and raise the running maximums
return Pick(triplets, target, i + 1, a, b, c)
|| Pick(triplets, target, i + 1, Math.Max(a, t[0]), Math.Max(b, t[1]), Math.Max(c, t[2]));
}
}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
- Create an empty list
valid. - For each triplet, keep it only if all three values are at most the matching target values.
- Start a merged triplet at (0, 0, 0).
- For each triplet in
valid, raise each merged coordinate with max. - Compare the merged triplet with the target in all three positions.
- 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 intovalid. - 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
| Time | O(n) |
|---|---|
| Space | O(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 == targetJavaTested in our runner
import java.util.*;
class Solution {
public boolean mergeTriplets(int[][] triplets, int[] target) {
List<int[]> valid = new ArrayList<>();
// keep only triplets that never exceed the target
for (int[] t : triplets) {
if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]) {
valid.add(t);
}
}
int[] merged = new int[3];
for (int[] t : valid) {
for (int i = 0; i < 3; i++) {
merged[i] = Math.max(merged[i], t[i]);
}
}
return merged[0] == target[0] && merged[1] == target[1] && merged[2] == target[2];
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
vector<vector<int>> valid;
// keep only triplets that never exceed the target
for (const auto& t : triplets) {
if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]) {
valid.push_back(t);
}
}
int merged[3] = {0, 0, 0};
for (const auto& t : valid) {
for (int i = 0; i < 3; i++) {
merged[i] = max(merged[i], t[i]);
}
}
return merged[0] == target[0] && merged[1] == target[1] && merged[2] == target[2];
}
};JavaScriptTested in our runner
/**
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target) {
// keep only triplets that never exceed the target
const valid = triplets.filter(
(t) => t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]
);
const merged = [0, 0, 0];
for (const t of valid) {
for (let i = 0; i < 3; i++) {
merged[i] = Math.max(merged[i], t[i]);
}
}
return merged[0] === target[0] && merged[1] === target[1] && merged[2] === target[2];
};GoTested in our runner
func mergeTriplets(triplets [][]int, target []int) bool {
valid := [][]int{}
// keep only triplets that never exceed the target
for _, t := range triplets {
if t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2] {
valid = append(valid, t)
}
}
merged := [3]int{0, 0, 0}
for _, t := range valid {
for i := 0; i < 3; i++ {
if t[i] > merged[i] {
merged[i] = t[i]
}
}
}
return merged[0] == target[0] && merged[1] == target[1] && merged[2] == target[2]
}C#Tested in our runner
public class Solution {
public bool mergeTriplets(int[][] triplets, int[] target) {
var valid = new List<int[]>();
// keep only triplets that never exceed the target
foreach (int[] t in triplets) {
if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2]) {
valid.Add(t);
}
}
int[] merged = new int[3];
foreach (int[] t in valid) {
for (int i = 0; i < 3; i++) {
merged[i] = Math.Max(merged[i], t[i]);
}
}
return merged[0] == target[0] && merged[1] == target[1] && merged[2] == target[2];
}
}
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
- Create three flags, all false, one per coordinate.
- Read the next triplet.
- If any of its values is above the matching target value, skip it.
- Otherwise, for each coordinate where the triplet equals the target, set that flag to true.
- Repeat until all triplets are read.
- 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.
| Step | Action | Exceeds target? | flag0 | flag1 | flag2 |
|---|---|---|---|---|---|
| 0 | start | no | false | false | false |
| 1 | read [1,1,1], check 1 > 1 for each position | no | false | false | false |
| 2 | position 0: 1 == 1 | no | true | false | false |
| 3 | position 1: 1 == 1 | no | true | true | false |
| 4 | position 2: 1 == 1 | no | true | true | true |
| 5 | no triplets left, return flag0 and flag1 and flag2 | no | true | true | true |
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
| Time | O(n) |
|---|---|
| Space | O(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)JavaTested in our runner
import java.util.*;
class Solution {
public boolean mergeTriplets(int[][] triplets, int[] target) {
boolean[] matched = new boolean[3];
for (int[] t : triplets) {
// a triplet above the target anywhere can never be used
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) {
continue;
}
for (int i = 0; i < 3; i++) {
if (t[i] == target[i]) {
matched[i] = true;
}
}
}
return matched[0] && matched[1] && matched[2];
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
bool matched[3] = {false, false, false};
for (const auto& t : triplets) {
// a triplet above the target anywhere can never be used
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) {
continue;
}
for (int i = 0; i < 3; i++) {
if (t[i] == target[i]) {
matched[i] = true;
}
}
}
return matched[0] && matched[1] && matched[2];
}
};JavaScriptTested in our runner
/**
* @param {number[][]} triplets
* @param {number[]} target
* @return {boolean}
*/
var mergeTriplets = function(triplets, target) {
const matched = [false, false, false];
for (const t of triplets) {
// a triplet above the target anywhere can never be used
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) {
continue;
}
for (let i = 0; i < 3; i++) {
if (t[i] === target[i]) {
matched[i] = true;
}
}
}
return matched[0] && matched[1] && matched[2];
};GoTested in our runner
func mergeTriplets(triplets [][]int, target []int) bool {
var matched [3]bool
for _, t := range triplets {
// a triplet above the target anywhere can never be used
if t[0] > target[0] || t[1] > target[1] || t[2] > target[2] {
continue
}
for i := 0; i < 3; i++ {
if t[i] == target[i] {
matched[i] = true
}
}
}
return matched[0] && matched[1] && matched[2]
}C#Tested in our runner
public class Solution {
public bool mergeTriplets(int[][] triplets, int[] target) {
bool[] matched = new bool[3];
foreach (int[] t in triplets) {
// a triplet above the target anywhere can never be used
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) {
continue;
}
for (int i = 0; i < 3; i++) {
if (t[i] == target[i]) {
matched[i] = true;
}
}
}
return matched[0] && matched[1] && matched[2];
}
}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 andcontinuebefore 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
orbetween the three comparisons, notand. - Comparing with
>=or==in the filter, such ast[i] != target[i]. Smaller values are harmless because the maximum ignores them. Reject only ont[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
Related problems
- Hand of Straights · same technique: Sorting Based
- Sort an Array · same technique: Sorting Based
- Two City Scheduling · same technique: Sorting Based
- Queue Reconstruction by Height · same technique: Sorting Based
- Candy · same technique: Sorting Based
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns