Merge triplets to form target triplet

August 9, 2022

greedy

Problem URL: Merge triplets to form target triplet

We will iterate through all the triplets and if we found any of the items are greater than the value of target triplet, we ignore it from the consideration. Then we check if we found a value which is equal to target triplet value, we will add the index to a good set, so we don't duplicate the index. After the iteration is done, if number of index in the good set is equal to 3, then it's possible to construct the target triplet.

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

        for t in triplets:
            if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:
                continue
            for i, val in enumerate(t):
                if val == target[i]:
                    good.add(i)

        return len(good) == 3

Time Complexity: O(n)
Space Complexity: O(1)