Skip to main content

Merge Triplets to Form Target Triplet

Medium
Data Structures and Algorithms
Editorial
Topics:
Array
Greedy
Iteration

You are given triplets, a list of triplets, where each triplet is an array of three integers. You are also given target, another three-integer array. A triplet's first, second, and third positions are treated independently as coordinates.

You may select any collection of triplets and merge them. Merging takes the maximum value at each coordinate across all selected triplets; for instance, the merged first coordinate is the largest first coordinate among the selected triplets. A triplet may be selected at most once, and the selected collection may contain one or more triplets.

Return true if some selection of triplets can be merged to produce exactly target; otherwise, return false. No coordinate of a selected triplet may exceed the corresponding coordinate of target, because merging uses coordinate-wise maximums.

Example 1:

Input: triplets = [[2,4,1],[1,3,5],[2,3,4]], target = [2,4,5]
Output: true
Explanation: The first two triplets are individually no larger than the target. Their coordinate-wise maximum is [2,4,5], so the target can be formed.

Example 2:

Input: triplets = [[4,1,2],[2,5,2],[3,2,6]], target = [3,5,2]
Output: false
Explanation: The first triplet exceeds the target in its first coordinate, and the third exceeds it in its third coordinate. The only remaining triplet cannot provide the target's first coordinate.

Example 3:

Input: triplets = [[1,2,3],[2,1,2],[1,2,2]], target = [2,2,3]
Output: true
Explanation: The first triplet supplies the third coordinate and the second triplet supplies the first; together their maximum is [2,2,3].

Constraints:

  • 1 <= triplets.length <= 10^5
  • triplets[i].length = 3 for every valid index i
  • 1 <= triplets[i][j] <= 10^3 for every valid index i and coordinate j
  • target.length = 3
  • 1 <= target[j] <= 10^3 for every coordinate j

Need help or want more practice?

Practise in an interviewGet AI Coach help