Merge Triplets to Form Target Triplet
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.
Examples
Constraints
1 <= triplets.length <= 10^5triplets[i].length == target.length == 31 <= ai, bi, ci, x, y, z <= 1000
Greedy Elimination
Approach
Since the operation always takes the maximum, if a triplet has *any* value strictly greater than the corresponding value in the `target` triplet, it can *never* be used. Using it would permanently ruin our chance of forming the target because the maximum operation only increases values. So, we iterate through all `triplets` and discard any triplet that has `a > target[0]`, `b > target[1]`, or `c > target[2]`. For all the remaining valid triplets, we merge them together by tracking the maximum values we've seen so far for the first, second, and third elements. If our tracked maximums eventually match `target[0]`, `target[1]`, and `target[2]`, we return true.
Complexity Analysis
Time complexity is O(n) as we only need to iterate through the array of triplets once. Space complexity is O(1) because we only use a few boolean variables or a small set to track progress.
class Solution { public boolean mergeTriplets(int[][] triplets, int[] target) { boolean matchFirst = false; boolean matchSecond = false; boolean matchThird = false; for (int[] t : triplets) { // Discard triplets that have any value greater than the target if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) { continue; } // Check if this valid triplet can help us reach the target components if (t[0] == target[0]) matchFirst = true; if (t[1] == target[1]) matchSecond = true; if (t[2] == target[2]) matchThird = true; // If all three components have been matched at some point, we are good if (matchFirst && matchSecond && matchThird) { return true; } } return false; }}