Algo-Sim › Greedy

Merge Triplets to Form Target Triplet

Medium · Greedy · step through it in Java, Python and C++ on your own input

Can merging (element-wise max) some triplets produce the target? Skip any triplet that exceeds the target anywhere, and check that the rest reach every coordinate.

Problem

You are given a list of integer triplets and a target triplet. Merging two triplets replaces one of them with their element-wise maximum, and you may merge as many times as you like. Return true if some sequence of merges can turn one of the triplets into exactly target.

Constraints

Edge cases to test

Follow-up questions

Why can bad triplets be ignored safely?
Merging takes the max, so a value above the target can never be undone; any triplet within the target can only help.
What about k-dimensional tuples?
The same filter-then-check scan works coordinate by coordinate: O(n·k) time, O(k) space.

Solution

Java

public boolean mergeTriplets(int[][] triplets, int[] target) {
    boolean[] found = 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]) {
                found[i] = true;
            }
        }
    }
    return found[0] && found[1] && found[2];
}

Python

def merge_triplets(triplets, target):
    found = [False] * 3
    for t in triplets:
        if t[0] > target[0] or t[1] > target[1] or t[2] > target[2]:
            continue
        for i in range(3):
            if t[i] == target[i]:
                found[i] = True
    return all(found)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool mergeTriplets(vector<vector<int>> &triplets, vector<int> &target) {
        vector<bool> found(3, false);
        for (const vector<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]) {
                    found[i] = true;
                }
            }
        }
        return found[0] && found[1] && found[2];
    }
};

More Greedy problems