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:
- Initialize variables
min_tripletto represent the smallest possible triplet (with arbitrary values), andresultto store the final answer. - Iterate through the array using two nested loops:
ias the outer loop, ranging from 0 toarr.length - 2, andjas the inner loop, ranging fromi + 1toarr.length - 1. - For each pair
(i, j), calculate the sum of elements at indicesi,j, andk = arr.length - 1. This represents a possible triplet. - Compare this new triplet with
min_triplet. If it's smaller (or equal), updatemin_triplet. - After iterating through all pairs, return
resultif 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
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;
}