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 (auto& t : triplets)
      if (equal(begin(t), end(t), begin(target),
                [](int a, int b) { return a <= b; }))
        transform(begin(t), end(t), begin(merged), begin(merged),
                  [](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[] t : triplets)
      if (t[0] <= target[0] && t[1] <= target[1] && t[2] <= target[2])
        for (int i = 0; i < target.length; ++i)
          merged[i] = Math.max(merged[i], t[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 t in triplets:
      if all(a <= b for a, b in zip(t, target)):
        for i in range(3):
          merged[i] = max(merged[i], t[i])

    return merged == target