Merge Triplets to Form Target Triplet - 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. You are also given an integer 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 (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].

For example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].

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

Input & Output

Example 1 — Basic Merge
$ Input: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]
Output: true
💡 Note: Merge triplets[0] and triplets[2]: [max(2,1), max(5,7), max(3,5)] = [2,7,5] which equals target
Example 2 — Impossible Target
$ Input: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]
Output: false
💡 Note: Target[1] = 2, but all triplets have second element ≥ 4, so we can never achieve 2 in position 1
Example 3 — Direct Match
$ Input: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]
Output: true
💡 Note: Can achieve [5,5,5] by merging multiple triplets: max positions give us 5,5,5

Constraints

  • 1 ≤ triplets.length ≤ 105
  • triplets[i].length == target.length == 3
  • 1 ≤ ai, bi, ci, x, y, z ≤ 1000

Visualization

Tap to expand
Merge Triplets to Form Target Triplet INPUT triplets array: 2 5 3 i=0 1 8 4 i=1 1 7 5 i=2 target: 2 7 5 Input Values: triplets = [ [2,5,3],[1,8,4],[1,7,5] ] target = [2,7,5] ALGORITHM STEPS 1 Filter Valid Triplets Keep only if all values <= target values 2 Check Each Triplet i=0: [2,5,3] OK (all <= target) i=1: [1,8,4] SKIP (8 > 7) i=2: [1,7,5] OK (all <= target) 3 Track Matches From [2,5,3]: found x=2 From [1,7,5]: found y=7, z=5 4 Verify Coverage All target values found? x=2 [OK] y=7 [OK] z=5 [OK] Valid Triplets Merge: [2,5,3] contributes: pos 0 [1,7,5] contributes: pos 1,2 max(2,1)=2, max(5,7)=7, max(3,5)=5 --> [2,7,5] FINAL RESULT Merged Result: 2 7 5 = Target: 2 7 5 OK OK OK Output: true Target triplet [2,7,5] can be obtained by merging valid triplets Key Insight: Greedy Filtering: Only consider triplets where ALL values are <= corresponding target values. If we can find triplets that together cover each position of the target with exact matches, then max operations will produce the target. Skip any triplet that would exceed any target value. TutorialsPoint - Merge Triplets to Form Target Triplet | Greedy Filtering Approach
Asked in
Google 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen