Merge Triplets to Form Target Triplet — LeetCode 1899 Python Solution

MediumGreedyArray
Problem
#1899
Pattern
Greedy
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

Python
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

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

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

On a study list

This problem is on NeetCode 150.

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.

Get Stealth Interview