700653. Triplet Family

Basic

Triplet Family

Slug: triplet-family Difficulty: Basic Id: 700653 Topic Tags: Arrays, Sorting, Data Structures, Algorithms Company Tags: Arcesium

Summary

The Triplet Family problem involves finding triplets in a given array that satisfy certain conditions. The key concepts involved are arrays and sorting.

A triplet is considered part of the "Triplet Family" if it satisfies three conditions:

  1. All elements are unique (no duplicates).
  2. Each element is greater than or equal to 0.
  3. The sum of any two elements is less than a given target value (T).

Detailed Explanation

To solve this problem, we can use a two-pointer technique along with sorting. Here's the step-by-step approach:

  1. First, sort the array in ascending order.
  2. Initialize three pointers: i, j, and k. Set i to 0 (the start of the array), j to i + 1, and k to the end of the array.
  3. Move the j pointer towards the end of the array while maintaining the following conditions:
    • The sum of elements at indices i, j, and k is less than or equal to T.
    • The element at index j is greater than or equal to 0.
  4. If the conditions are met, increment i by 1 and update j to i + 1. This ensures that we consider all possible triplets without duplicates.
  5. Repeat steps 3-4 until k reaches the end of the array.
  6. When k reaches the end, decrement it and update i to k - 1, then repeat step 3.
  7. Continue this process until j is less than or equal to k. This ensures that we have considered all possible triplets.

The time complexity of this algorithm is O(n^2), where n is the size of the array, and the space complexity is O(1) since we only use a few extra variables.

Optimized Solutions

Java

View on GeeksforGeeks
public class TripletFamily {
    public static void findTriplets(int[] arr, int T) {
        Arrays.sort(arr);
        for (int i = 0; i < arr.length - 2; i++) {
            int j = i + 1;
            int k = arr.length - 1;
            while (j < k && arr[i] + arr[j] + arr[k] > T) {
                k--;
            }
            while (j < k && arr[i] + arr[j] + arr[k] <= T) {
                System.out.println(arr[i] + " " + arr[j] + " " + arr[k]);
                j++;
                k--;
            }
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.