#1899

Merge Triplets to Form Target Triplet

Medium
ArrayGreedyGreedyArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all pairs, we can directly find the maximum values from the triplets and check if they match the target. This is more efficient and avoids unnecessary comparisons.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize max_a, max_b, and max_c to 0.
  2. 2Step 2: Iterate through each triplet and update max_a, max_b, and max_c with the maximum values found in the triplets that do not exceed the target values.
  3. 3Step 3: After processing all triplets, check if max_a equals target[0], max_b equals target[1], and max_c equals target[2]. If they match, return true; otherwise, return false.
solution.py10 lines
1# Full working Python code
2
3def mergeTriplets(triplets, target):
4    max_a, max_b, max_c = 0, 0, 0
5    for a, b, c in triplets:
6        if a <= target[0] and b <= target[1] and c <= target[2]:
7            max_a = max(max_a, a)
8            max_b = max(max_b, b)
9            max_c = max(max_c, c)
10    return max_a == target[0] and max_b == target[1] and max_c == target[2]

Complexity note: The time complexity is O(n) since we only need to iterate through the triplets once. The space complexity is O(1) because we are using a fixed amount of extra space.

  • 1We only care about triplets that can contribute to the target values.
  • 2The maximum values from the triplets must match the target values exactly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.