Start learning free

LESSON 513 OF 640 · GREEDY

Merge Triplets to Form Target Triplet in Swift

Practice O(n)

You get an array triplets. Each triplet is a group of three numbers. You also get one more triplet, target.

Return true if you can merge some of the triplets into exactly target. Otherwise, return false.

Merging two triplets keeps the larger value in each position. For example, merging [7,1,4] and [2,6,3] gives [7,6,4].

You can merge as many triplets as you like, in any order. A single triplet counts too, with no merging at all.

 

Example 1:

Input: triplets = [[1,6,3],[7,2,2],[3,3,8]], target = [7,6,8]
Output: true
Explanation: Merge all three triplets.
The first position takes the 7 of [7,2,2].
The second takes the 6 of [1,6,3].
The third takes the 8 of [3,3,8].

Example 2:

Input: triplets = [[3,1,6],[8,4,2],[1,2,2]], target = [3,4,6]
Output: false
Explanation: Only [8,4,2] has a 4 in the middle.
But its first value is 8, and target's is 3.
Any merge that uses [8,4,2] starts with 8 or more.

Example 3:

Input: triplets = [[5,9,9],[7,3,8],[5,3,8]], target = [5,3,8]
Output: true
Explanation: The last triplet is already [5,3,8].
No merge is needed.

 

Constraints:

  • 1 to 100,000 triplets.
  • Every value is a whole number from 1 to 1,000.

Note:

Your solution should run in O(n) time.

STEP 1 OF 6
    Ctrl + Enter to check

    Merge Triplets To Form Target Triplet in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free