InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Merge Triplets to Form Target Triplet

medium Original ↗ 00:00

Problem

You are given a list of triplets, where triplets[i] = [a, b, c], and a target = [x, y, z]. You may repeatedly perform this operation: pick two triplets triplets[i] and triplets[j], and replace triplets[i] with their component-wise maximum [max(ai, aj), max(bi, bj), max(ci, cj)]. (You may reuse any triplet as j as many times as you like.)

Return True if, after some sequence of operations, at least one triplet in the list becomes exactly equal to target; otherwise return False.

Examples

  • triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]True — merge [2,5,3] with [1,7,5] to get [2,7,5].
  • triplets = [[3,4,5],[4,5,6]], target = [3,2,5]False — every triplet has a second component ≥ 4 > 2, so the y = 2 slot can never be reached.
  • triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]True[2,5,3] supplies the 5 in slot 2, [1,2,5] supplies the 5 in slot 3, [5,2,3] supplies the 5 in slot 1; none overshoots.

Constraints

  • 1 <= len(triplets) <= 10^5
  • 1 <= ai, bi, ci, x, y, z <= 1000
  • The 10^5 bound rules out anything exponential in the number of triplets; a single linear pass is expected.

Think about it first

Hint 1 The merge operation is component-wise max. Max never decreases a value. So if a triplet has any component larger than the target's, merging it in raises that slot above the target permanently.
Hint 2 Call a triplet "safe" if a <= x and b <= y and c <= z. Only safe triplets can ever participate in building the target. Unsafe ones cannot contribute.
Hint 3 Merging all the safe triplets together can only help. So the real question is: among the safe triplets, does some triplet hit a == x, some hit b == y, and some hit c == z? If all three target values are achievable from safe triplets, the answer is yes.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug