Skip to content
Related Articles

Related Articles

Improve Article
Triplets in array with absolute difference less than k
  • Difficulty Level : Medium
  • Last Updated : 05 May, 2021

Given an array A[] of n elements and an integer k. The task is to find the number of triplet (x, y, k), where 0 <= x, y, k < n and x, y, k are the index in the array A[] such that: 
|A[x] – A[y]| <= k 
|A[y] – A[z]| <= k 
|A[z] – A[x]| <= k
Examples: 
 

Input : A[] = { 1, 1, 2, 2, 3 }, k = 1
Output : 5
(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3),
(2, 3, 4) are the triplet whose element will 
satisfy the above three condition.

Input : A[] = { 1, 2, 3 }, k = 1
Output : 0

 

A simple solution is to run three nested loops and count triplets with given constraints.
An efficient solution is based on the fact rearranging the elements in the array does not affect the answer because basically, we want index x, y, z to be in increasing order, not A[x], A[y], A[z] to be sorted. Suppose, A[x] is at index y, A[y] at z, A[z] at x, still we can pick the triplet (x, y, z) because the condition of difference between any two elements to be less k still stands. 
Now, to calculate the number of triplet indices (x, y, z) which satisfies the above condition, we will sort the given array. Now, for each element A[i], i >= 2, we will find the lower bound index of A[i] – k, say lb. Now, observe all the element between index lb and i are less than A[i] and the difference between any teo elements will be less than or equal to k. So, element at index i can be treated as index z and we can choose any two element from lb to i – 1. So, this will increase the count of the triplet by i – lbC2
Below is the implementation of this approach: 
 

C++




// CPP program to count triplets with difference less
// than k.
#include <bits/stdc++.h>
using namespace std;
 
// Return the lower bound i.e smallest index of
// element having value greater or equal to value
int binary_lower(int value, int arr[], int n)
{
    int start = 0;
    int end = n - 1;
    int ans = -1;
    int mid;
 
    while (start <= end) {
        mid = (start + end) / 2;
        if (arr[mid] >= value) {
            end = mid - 1;
            ans = mid;
        }
        else {
            start = mid + 1;
        }
    }
    return ans;
}
 
// Return the number of triplet indices satisfies
// the three constraints
int countTriplet(int arr[], int n, int k)
{
    int count = 0;
 
    // sort the array
    sort(arr, arr + n);
 
    // for each element from index 2 to n - 1.
    for (int i = 2; i < n; i++) {
 
        // finding the lower bound of arr[i] - k.
        int cur = binary_lower(arr[i] - k, arr, n);
 
        // If there are at least two elements between
        // lower bound and current element.
        if (cur <= i - 2) {
 
            // increment the count by lb - i C 2.
            count += ((i - cur) * (i - cur - 1)) / 2;
        }
    }
 
    return count;
}
int main()
{
    int arr[] = { 1, 1, 2, 2, 3 };
    int k = 1;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << countTriplet(arr, n, k) << endl;
    return 0;
}

Java




// Java program to count triplets
// with difference less than k.
import java.io.*;
import java .util.*;
 
class GFG
{
 
// Return the lower bound i.e
// smallest index of element
// having value greater or
// equal to value
static int binary_lower(int value,
                        int arr[],
                        int n)
{
    int start = 0;
    int end = n - 1;
    int ans = -1;
    int mid;
 
    while (start <= end)
    {
        mid = (start + end) / 2;
        if (arr[mid] >= value)
        {
            end = mid - 1;
            ans = mid;
        }
        else
        {
            start = mid + 1;
        }
    }
    return ans;
}
 
// Return the number of
// triplet indices satisfies
// the three constraints
static int countTriplet(int arr[],
                        int n, int k)
{
    int count = 0;
 
    // sort the array
    Arrays.sort(arr);
 
    // for each element from
    // index 2 to n - 1.
    for (int i = 2; i < n; i++)
    {
 
        // finding the lower
        // bound of arr[i] - k.
        int cur = binary_lower(arr[i] - k,
                               arr, n);
 
        // If there are at least two
        // elements between lower
        // bound and current element.
        if (cur <= i - 2)
        {
 
            // increment the count
            // by lb - i C 2.
            count += ((i - cur) *
                      (i - cur - 1)) / 2;
        }
    }
    return count;
}
 
// Driver Code
public static void main (String[] args)
{
    int arr[] = {1, 1, 2, 2, 3};
    int k = 1;
    int n = arr.length;
     
    System.out.println(countTriplet(arr, n, k));
}
}
 
// This code is contributed by anuj_67.

Python 3




# Python 3 program to count
# triplets with difference less
# than k.
 
# Return the lower bound
# i.e smallest index of
# element having value greater
# or equal to value
def binary_lower(value, arr, n):
 
    start = 0
    end = n - 1
    ans = -1
 
    while (start <= end) :
        mid = (start + end) // 2
        if (arr[mid] >= value) :
            end = mid - 1
            ans = mid
         
        else :
            start = mid + 1
             
    return ans
 
# Return the number of triplet
# indices satisfies
# the three constraints
def countTriplet(arr, n, k):
 
    count = 0
 
    # sort the array
    arr.sort()
 
    # for each element from
    # index 2 to n - 1.
    for i in range(2, n) :
 
        # finding the lower bound
        # of arr[i] - k.
        cur = (binary_lower(arr[i] - k
                            , arr, n))
 
        # If there are at least
        # two elements between
        # lower bound and current element.
        if (cur <= i - 2) :
 
            # increment the count by
            # lb - i C 2.
            count += ((i - cur) *
                     (i - cur - 1)) // 2
 
    return count
     
# Driver code       
if __name__ == "__main__":
    arr = [ 1, 1, 2, 2, 3 ]
    k = 1
    n = len(arr)
 
    print(countTriplet(arr, n, k))
 
# This code is contributed by
# ChitraNayal

C#




// C# program to count triplets
// with difference less than k.
using System;
 
class GFG
{
 
// Return the lower bound i.e
// smallest index of element
// having value greater or
// equal to value
static int binary_lower(int value,
                        int []arr,
                        int n)
{
    int start = 0;
    int end = n - 1;
    int ans = -1;
    int mid;
 
    while (start <= end)
    {
        mid = (start + end) / 2;
        if (arr[mid] >= value)
        {
            end = mid - 1;
            ans = mid;
        }
        else
        {
            start = mid + 1;
        }
    }
    return ans;
}
 
// Return the number of
// triplet indices satisfies
// the three constraints
static int countTriplet(int []arr,
                        int n, int k)
{
    int count = 0;
 
    // sort the array
    Array.Sort(arr);
 
    // for each element from
    // index 2 to n - 1.
    for (int i = 2; i < n; i++)
    {
 
        // finding the lower
        // bound of arr[i] - k.
        int cur = binary_lower(arr[i] - k,
                               arr, n);
 
        // If there are at least two
        // elements between lower
        // bound and current element.
        if (cur <= i - 2)
        {
 
            // increment the count
            // by lb - i C 2.
            count += ((i - cur) *
                      (i - cur - 1)) / 2;
        }
    }
    return count;
}
 
// Driver Code
public static void Main ()
{
    int []arr = {1, 1, 2, 2, 3};
    int k = 1;
    int n = arr.Length;
     
    Console.WriteLine(countTriplet(arr, n, k));
}
}
 
// This code is contributed by anuj_67.

Javascript




<script>
 
// Javascript program to count triplets with difference less
// than k.
 
// Return the lower bound i.e smallest index of
// element having value greater or equal to value
function binary_lower(value, arr, n)
{
    var start = 0;
    var end = n - 1;
    var ans = -1;
    var mid;
 
    while (start <= end) {
        mid = parseInt((start + end) / 2);
        if (arr[mid] >= value) {
            end = mid - 1;
            ans = mid;
        }
        else {
            start = mid + 1;
        }
    }
    return ans;
}
 
// Return the number of triplet indices satisfies
// the three constraints
function countTriplet(arr, n, k)
{
    var count = 0;
 
    // sort the array
    arr.sort((a,b)=>a-b)
 
    // for each element from index 2 to n - 1.
    for (var i = 2; i < n; i++) {
 
        // finding the lower bound of arr[i] - k.
        var cur = binary_lower(arr[i] - k, arr, n);
 
        // If there are at least two elements between
        // lower bound and current element.
        if (cur <= i - 2) {
 
            // increment the count by lb - i C 2.
            count += parseInt(((i - cur) * (i - cur - 1)) / 2);
        }
    }
 
    return count;
}
 
// Driver code
var arr = [ 1, 1, 2, 2, 3 ];
var k = 1;
var n = arr.length;
document.write( countTriplet(arr, n, k));
 
// This code is contributed by rrrtnx.
</script>

Output: 
 

5

 
Complexity: O(nlogn)
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :