702809. Happiest Triplet

Medium

Happiest Triplet

Slug: happiest-triplet2921

Difficulty: Medium

Id: 702809

Topic Tags: Arrays, Searching, Sorting, Data Structures, Algorithms

Company Tags: None

Summary

Find three indices i, j, and k in an array such that the triplet (arr[i], arr[j], arr[k]) is the smallest possible. If no such triplet exists, return -1.

The problem involves manipulating arrays to find specific patterns, which requires efficient searching and sorting algorithms.

Detailed Explanation

To solve this problem, we can use a simple approach by iterating through the array and keeping track of the minimum triplet found so far. We compare each triplet with the current minimum and update it if necessary.

Here's a step-by-step breakdown of the solution:

  1. Initialize variables min_triplet to represent the smallest possible triplet (with arbitrary values), and result to store the final answer.
  2. Iterate through the array using two nested loops: i as the outer loop, ranging from 0 to arr.length - 2, and j as the inner loop, ranging from i + 1 to arr.length - 1.
  3. For each pair (i, j), calculate the sum of elements at indices i, j, and k = arr.length - 1. This represents a possible triplet.
  4. Compare this new triplet with min_triplet. If it's smaller (or equal), update min_triplet.
  5. After iterating through all pairs, return result if the minimum triplet was found; otherwise, return -1.

Time complexity: O(n^2) due to nested loops. Space complexity: O(1) as we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int findHappiestTriplet(int[] arr) {
    int min_triplet = Integer.MAX_VALUE;
    for (int i = 0; i < arr.length - 2; i++) {
        for (int j = i + 1; j < arr.length - 1; j++) {
            int sum = arr[i] + arr[j] + arr[arr.length - 1];
            if (sum < min_triplet) {
                min_triplet = sum;
            }
        }
    }
    return min_triplet == Integer.MAX_VALUE ? -1 : min_triplet;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.