Algorithms · Visualized
Merge Triplets to Form Target Triplet
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given triplets of 3 numbers each, and a target triplet, determine if you can select some triplets and 'merge' them (taking the max of each position across selected triplets) to exactly form the target. Time: O(n) average, O(n), where n is the number of triplets worst; space: O(1).
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Merge Triplets to Form Target Triplet
GreedyGiven triplets of 3 numbers each, and a target triplet, determine if you can select some triplets and 'merge' them (taking the max of each position across selected triplets) to exactly form the target. The greedy filter: only consider triplets where no value exceeds the corresponding target value (an 'oversized' triplet would ruin the merge), then check if the max of each position across the valid ones hits the target exactly.
How Merge Triplets to Form Target Triplet Works
- Go through each triplet and discard any triplet that has any single value greater than the corresponding target value (it would push that position too high if used).
- For the remaining valid triplets, track the maximum value seen so far at each of the three positions.
- Update these three running maximums as you process each valid triplet.
- After processing all valid triplets, compare the three running maximums to the target triplet.
- If all three match exactly, it's possible to form the target; otherwise, it isn't.
Merge Triplets to Form Target Triplet Worked Example
Input: {triplets: [[2, 5, 3], [1, 8, 4], [1, 7, 5]], target: [2, 7, 5]}
Check [2,5,3]: all values ≤ target[2,7,5] → valid, running max=[2,5,3]. Check [1,8,4]: 8>7 (target position1) → discard, oversized. Check [1,7,5]: all ≤ target → valid, running max=[max(2,1),max(5,7),max(3,5)]=[2,7,5]. Final running max [2,7,5] matches target exactly — possible, return true.
| x | y | z | |
|---|---|---|---|
| T0 | 2 | 5 | 3 |
| T1 | 1 | 8 | 4 |
| T2 | 1 | 7 | 5 |
def merge_triplets(triplets, target):
ok = [False, False, False]
for t in triplets:
if all(t[i] <= target[i] for i in range(3)):
for i in range(3):
ok[i] |= t[i] == target[i]
return all(ok)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Merge Triplets to Form Target Triplet Time & Space Complexity
When to Use Merge Triplets to Form Target Triplet
- Combining resource/stat bundles (e.g. game character stats) to exactly hit a target profile without overshooting any stat.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.