You have a list of triplets, each a list of three integers, and one more triplet, target. You may combine triplets as often as you like: pick two different triplets and replace the second one with their position-by-position maximum. For instance, combining [4, 1, 6] into [2, 3, 5] turns it into [4, 3, 6].
Return true if, after some number of these moves (zero is allowed), one of the triplets in the list is exactly equal to target. Return false otherwise.
Example 1
Input: triplets = [[1,4,2],[3,2,5],[2,6,1],[3,1,1]], target = [3,4,5] Output: true Why: combining [1,4,2] and [3,2,5] gives [3,4,5]
2 more examples and the constraints
Example 2
Input: triplets = [[2,3,1],[1,1,4]], target = [2,3,3] Output: false Why: no triplet that stays within the target has a 3 in the last spot
Example 3
Input: triplets = [[6,6,6]], target = [6,6,6] Output: true Why: the target is already in the list
Constraints
- 1 ≤ number of triplets ≤ 100,000
- Every triplet, and the target, has exactly 3 numbers
- Every number is between 1 and 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Grow each triplet in turnO(n²)
- Merge only the safe onesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 triplets | Verdict |
|---|---|---|---|
| Grow each triplet in turn | O(n²) | Mention it, then move on | |
| Merge only the safe ones | O(n) | Best; one pass |
n = number of triplets.
Edge cases to test
- Target already present. [[6,6,6]] with target [6,6,6] is true with zero moves.
- Right number, wrong company. [3,9,1] has the 3 you need, but its 9 overshoots, so it cannot be used.
- Every triplet too big. Nothing is safe, best stays [0, 0, 0], and the answer is false.
- One spot from each triplet. [3,1,1], [1,4,1], [1,1,5] combine to [3,4,5].
Common mistakes
- Accepting a triplet because it contains one target value, without checking its other two numbers.
- Merging only the triplets that match a target value, then missing that safe ones never hurt.
- Trying to find a specific order of moves; the order never matters for a max.
How to talk through it
- 1Clarify. Can a triplet be used in more than one merge? Does zero moves count? Are all values positive?
- 2Give the brute force. Grow each triplet with every safe one; say it is O(n²).
- 3Use the property of max. Max only grows, so anything above the target is out, and everything else is free to add.
- 4Code one pass. Filter by the three comparisons and keep a running max.
- 5Test out loud. Run the overshooting-neighbour case and the all-too-big case before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?