1899. Merge Triplets to Form Target Triplet
Medium NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Greedy
- Time
- O(n)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven triplets, you may take element-wise maxima of any chosen triplets; decide whether you can produce exactly the target triplet.
Approach
Key idea: Only triplets that never exceed the target in any position can contribute, since one over-large value can never be lowered. Among the usable triplets, check that each target coordinate is achievable by some triplet.
Steps:
- Skip any triplet that has a component greater than the corresponding target component.
- For each remaining triplet, mark which positions equal the target value.
- Return true only if all three positions get matched.
class Solution {
public:
bool mergeTriplets(vector<vector<int>>& triplets, vector<int>& target) {
bool m0 = false, m1 = false, m2 = false;
for (auto& t : triplets) {
if (t[0] > target[0] || t[1] > target[1] || t[2] > target[2]) continue;
if (t[0] == target[0]) m0 = true;
if (t[1] == target[1]) m1 = true;
if (t[2] == target[2]) m2 = true;
}
return m0 && m1 && m2;
}
}; Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.