1899. Merge Triplets to Form Target Triplet
Asked at 1Google20
Problem
You may repeatedly pick two triplets and replace the second with their element-wise maximum. Decide whether target can end up as one of the triplets.
Example: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5] → true
Constraints: up to 10⁵ triplets.
Ignore any triplet with a value exceeding the target in some coordinate (it would poison the max). Among the rest, check that each target coordinate is matched by at least one.
Complexity: O(n).
class Solution:
def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:
good = set()
for t in triplets:
if all(t[i] <= target[i] for i in range(3)):
good |= {i for i in range(3) if t[i] == target[i]}
return len(good) == 3
assert Solution().mergeTriplets([[2, 5, 3], [1, 8, 4], [1, 7, 5]], [2, 7, 5]) is True
assert Solution().mergeTriplets([[3, 4, 5], [4, 5, 6]], [3, 2, 5]) is False
class Solution {
public boolean mergeTriplets(int[][] triplets, int[] target) {
boolean[] good = new boolean[3];
for (int[] t : triplets) {
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) continue;
for (int i = 0; i < 3; i++) if (t[i] == target[i]) good[i] = true;
}
return good[0] && good[1] && good[2];
}
}
func mergeTriplets(triplets [][]int, target []int) bool {
good := [3]bool{}
for _, t := range triplets {
if t[0] > target[0] || t[1] > target[1] || t[2] > target[2] {
continue // merging it would overshoot
}
for i := 0; i < 3; i++ {
if t[i] == target[i] {
good[i] = true
}
}
}
return good[0] && good[1] && good[2]
}