Skip to content

1899. Merge Triplets to Form Target Triplet 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
    vector<int> merged(target.size());

    for (const vector<int>& triplet : triplets)
      if (equal(triplet.begin(), triplet.end(), target.begin(),
                [](int a, int b) { return a <= b; }))
        transform(triplet.begin(), triplet.end(), merged.begin(),
                  merged.begin(), [](int a, int b) { return max(a, b); });

    return merged == target;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public boolean mergeTriplets(int[][] triplets, int[] target) {
    int[] merged = new int[target.length];

    for (int[] triplet : triplets)
      if (triplet[0] <= target[0] && triplet[1] <= target[1] && triplet[2] <= target[2])
        for (int i = 0; i < target.length; ++i)
          merged[i] = Math.max(merged[i], triplet[i]);

    return Arrays.equals(merged, target);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def mergeTriplets(self, triplets: list[list[int]], target: list[int]) -> bool:
    merged = [0] * len(target)

    for triplet in triplets:
      if all(a <= b for a, b in zip(triplet, target)):
        for i in range(3):
          merged[i] = max(merged[i], triplet[i])

    return merged == target