githubEdit

06. Happiest Triplet

βœ… GFG solution to the Happiest Triplet problem: find the triplet with minimum difference across three arrays using three-pointer technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

You are given three arrays a[], b[], c[] of the same size. Find a triplet such that (maximum - minimum) in that triplet is the minimum of all the triplets. A triplet should be selected so that it should have one number from each of the three given arrays. This triplet is the happiest among all the possible triplets. Print the triplet in decreasing order.

Note: If there are 2 or more smallest difference triplets, then the one with the smallest sum of its elements should be displayed.

πŸ“˜ Examples

Example 1

Input: a[] = [5, 2, 8], b[] = [10, 7, 12], c[] = [9, 14, 6]
Output: [7, 6, 5]
Explanation: The triplet [5, 7, 6] has difference (maximum - minimum) = (7 - 5) = 2 
which is minimum of all triplets.

Example 2

Input: a[] = [15, 12, 18, 9], b[] = [10, 17, 13, 8], c[] = [14, 16, 11, 5]
Output: [11, 10, 9]
Explanation: Multiple triplets have the same minimum difference, and among them 
[11, 10, 9] has the smallest sum, so it is chosen.

πŸ”’ Constraints

  • $1 \le \text{a.size()}, \text{b.size()}, \text{c.size()} \le 10^5$

  • $1 \le \text{a}[i], \text{b}[i], \text{c}[i] \le 10^5$

βœ… My Approach

The optimal approach uses the Three Pointers + Sorting technique to efficiently find the triplet with minimum difference:

Three Pointers Algorithm

  1. Sort All Arrays:

    • Sort arrays a[], b[], and c[] in ascending order.

    • This allows us to use greedy pointer movement strategy.

  2. Initialize Pointers:

    • Use three pointers i, j, k starting at index 0 for arrays a, b, c respectively.

    • Track minDiff to store the minimum difference found.

    • Store result triplet in decreasing order.

  3. Calculate Triplet Difference:

    • For current triplet (a[i], b[j], c[k]), find minimum and maximum values.

    • Calculate difference: maxVal - minVal.

    • Also calculate middle value: sum - maxVal - minVal.

  4. Update Result:

    • If current difference is smaller than minDiff, update result.

    • Store triplet in decreasing order: [maxVal, midVal, minVal].

  5. Move Pointer:

    • To minimize difference, increment the pointer pointing to the smallest value.

    • This greedy approach brings the minimum closer to maximum.

  6. Continue Until End:

    • Repeat until any pointer reaches the end of its array.

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n log n + m log m + p log p), where n, m, p are the sizes of arrays a, b, c respectively. Sorting dominates the time complexity, while the three-pointer traversal takes O(n + m + p) time as each pointer moves at most once through its array.

  • Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables. The sorting operation may use O(log n) space for recursion stack, but this is not counted as auxiliary space.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Sum-Aware Three Pointer Approach

πŸ’‘ Algorithm Steps:

  1. Sort all three arrays to enable ordered traversal.

  2. Use three pointers initialized at the start of each array.

  3. For each triplet, calculate both difference and sum.

  4. Update result if difference is smaller, or if difference is equal but sum is smaller.

  5. Move the pointer pointing to minimum value forward.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n + m log m + p log p) - Sorting dominates

  • Auxiliary Space: πŸ’Ύ O(1) - Constant extra space

βœ… Why This Approach?

  • Handles tie-breaking by sum correctly

  • Considers multiple criteria for optimization

  • More accurate for edge cases with equal differences

πŸ“Š 3️⃣ Explicit Variable Tracking

πŸ’‘ Algorithm Steps:

  1. Sort input arrays for efficient pointer movement.

  2. Track best difference and corresponding triplet separately.

  3. Calculate all three values (min, mid, max) explicitly.

  4. Update result when better triplet is found.

  5. Advance pointer of minimum element.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n + m log m + p log p) - Sorting dominates

  • Auxiliary Space: πŸ’Ύ O(1) - Only scalar variables

βœ… Why This Approach?

  • Clear variable naming for readability

  • Explicit tracking of all three values

  • Easy to debug and understand

πŸ“Š 4️⃣ Compact Implementation

πŸ’‘ Algorithm Steps:

  1. Sort all arrays for ordered processing.

  2. Use minimal variables for space efficiency.

  3. Compute difference and update result in single pass.

  4. Increment smallest element's pointer for convergence.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n log n + m log m + p log p) - Sorting operation dominates

  • Auxiliary Space: πŸ’Ύ O(1) - Minimal variable usage

βœ… Why This Approach?

  • Most compact code implementation

  • Efficient memory usage

  • Optimal for competitive programming

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🏷️ Main Approach

🟒 O(n log n)

🟒 O(1)

πŸš€ Clean and optimal

πŸ”§ Doesn't handle sum tie-breaking

πŸ” Sum-Aware

🟒 O(n log n)

🟒 O(1)

πŸ“– Handles all edge cases

πŸ”„ Slightly more comparisons

πŸ“Š Explicit Variables

🟒 O(n log n)

🟒 O(1)

🎯 Very readable

🐌 More variable declarations

πŸ”„ Compact

🟒 O(n log n)

🟒 O(1)

⭐ Minimal code size

πŸ”§ Less readable variable names

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… All test cases including ties

πŸ₯‡ Sum-Aware

β˜…β˜…β˜…β˜…β˜…

πŸ“– Code readability priority

πŸ₯ˆ Explicit Variables

β˜…β˜…β˜…β˜…β˜…

πŸ”§ Competitive programming speed

πŸ₯‰ Compact

β˜…β˜…β˜…β˜…β˜†

🎯 Basic implementation

πŸ… Main Approach

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. Let's make this learning journey more collaborative!

⭐ If you find this helpful, please give this repository a star! ⭐


πŸ“Visitor Count

Visitor counter

Last updated