InterviewPrepKit

Home / Coding / Greedy

Merge Triplets to Form Target Triplet

medium Original β†—
Solving tips
  • Key insight: merging is component-wise max, which never decreases a value, so any triplet with a component exceeding the target is permanently disqualified.
  • Merging all 'safe' triplets (every component <= target) is free and never hurts, so the target is reachable iff safe triplets jointly hit x, y, and z.
  • In one pass, only credit a slot hit when the whole triplet is safe AND that component equals the target β€” both conditions matter.
  • Target O(n) time and O(1) space; no subset search or merge simulation is needed.

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 permanently ruins that slot.
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 are useless (and harmful).
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.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.