MediumNo. 1899

Merge Triplets to Form Target Triplet — LeetCode 1899 Python Solution

Pattern
Greedy
Topics
Greedy, Array
On a study list
NeetCode 150
Reading time
2 min

The problem

A triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet.

Example

Input
triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output
true
Explanation
Perform the following operations:

Python solution

PythonSolution
class Solution:
    def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
        x, y, z = target
        d = e = f = 0
        for a, b, c in triplets:
            if a <= x and b <= y and c <= z:
                d = max(d, a)
                e = max(e, b)
                f = max(f, c)
        return [d, e, f] == target

Complexity

Time
O(n log n)
Space · auxiliary
O(1) to O(n)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1899. Merge Triplets to Form Target Triplet is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0011Container With Most WaterMedium
0134Gas StationMedium
0135CandyHard
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0330Patching ArrayHard

Frequently asked questions

How hard is LeetCode 1899. Merge Triplets to Form Target Triplet?

LeetCode 1899. Merge Triplets to Form Target Triplet is rated Medium on LeetCode.

What topics does LeetCode 1899. Merge Triplets to Form Target Triplet cover?

LeetCode 1899. Merge Triplets to Form Target Triplet is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.