AAlgoLoopSpaced repetition for LeetCode
MEDIUMGreedyLeetCode ↗

Merge Triplets to Form Target Triplet

The key idea

The merge operation only ever takes the element-wise maximum, so it can never decrease a value. A triplet that has any component strictly greater than the matching component of target is poison: merging it would push that position above target forever. Discard those triplets, then check whether the element-wise max of the survivors hits every target component exactly.

Problem

You are given a 2D array of integers triplets, where triplets[i] = [ai, bi, ci] describes the i-th triplet. You are also given an array target = [x, y, z] that describes the triplet you want to obtain.

To obtain target, you may apply the following operation on triplets any number of times (possibly zero):

- Choose two indices i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].

Return true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.

Constraints

Examples

Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] Output: true
Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5] Output: false
Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5] Output: true

Complexity

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

See the full solution

410310
Step-by-step visualization
Start free →

More Greedy problems