Open In App

Count triplets from a sorted array having difference between adjacent elements equal to D

Last Updated : 25 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a sorted array arr[] consisting of N positive integers and an integer D, the task is to find the number of triplets (i, j, k) such that arr[j] – arr[i] = D and arr[k] – arr[j] = D and 0 ? i < j < k < N.

Examples:

Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 3
Output: 3
Explanation:
Following are the triplets having the difference between the adjacent elements is D(= 3) are:

  1. {1, 4, 7}
  2. {4, 7, 10}
  3. {2, 5, 8}

Therefore, the total count of triplets is 3.

Input: arr[] = {1, 2, 4, 5, 7, 8, 10}, D = 1
Output: 0

Naive Approach: The simplest approach to solve this problem is to generate all the triplets of the given array and count those triplets having the difference between the adjacent elements is D(= 3).

Time Complexity: O(N3)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by considering every element of the array as the last element of the triplet and check for the previous two elements i.e., (arr[i] – D) and (arr[i] – 2 * D) exists in the array or not. Follow the steps below to solve the problem.

  • Initialize a HashMap, say M that stores the frequency of the array elements.
  • Initialize a variable, say ans as 0.
  • Traverse the given array arr[] and perform the following steps:
    • Increment the frequency of arr[i] by 1 in the HashMap M.
    • Now, check if the element (arr[i] – D) and (arr[i] – 2 * D) are present in the HashMap or not. If found to be true, then increment the value of ans by  freq[arr[i] – D] * freq[arr[i] – 2 * D].
  • After completing the above steps, print the value of ans as the resultant count of triplets in the array.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
int countTriplets(int D, vector<int>& arr)
{
    // Stores the frequency
    // of array elements
    unordered_map<int, int> freq;
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < arr.size(); i++) {
 
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.find(arr[i] - D)
                != freq.end()
            && freq.find(arr[i] - 2 * D)
                   != freq.end()) {
 
            // Update the value of ans
            ans += freq[arr[i] - D]
                   * freq[arr[i] - 2 * D];
        }
 
        // Increase the frequency
        // of the current element
        freq[arr[i]]++;
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr{ 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
    cout << countTriplets(D, arr);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
static int countTriplets(int D, int []arr)
{
     
    // Stores the frequency
    // of array elements
    HashMap<Integer,
            Integer> freq = new HashMap<Integer,
                                        Integer>();
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for(int i = 0; i < arr.length; i++)
    {
         
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.containsKey(arr[i] - D) &&
            freq.containsKey(arr[i] - 2 * D))
        {
             
            // Update the value of ans
            ans += freq.get(arr[i] - D) *
                   freq.get(arr[i] - 2 * D);
        }
 
        // Increase the frequency
        // of the current element
        if (freq.containsKey(arr[i]))
        {
            freq.put(arr[i], freq.get(arr[i]) + 1);
        }
        else
        {
            freq.put(arr[i], 1);
        }
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int []arr = { 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
     
    System.out.print(countTriplets(D, arr));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program for the above approach
 
# Function to count the number of
# triplets having difference
# between adjacent  elements equal to D
def countTriplets(D, arr):
     
    # Stores the frequency
    # of array elements
    freq = {}
 
    # Stores the count of
    # resultant triplets
    ans = 0
  
    # Traverse the array
    for i in range(len(arr)):
         
        # Check if arr[i] - D and
        # arr[i] - 2 * D  exists
        # in the Hashmap or not
        if (((arr[i] - D) in freq) and
             (arr[i] - 2 * D) in freq):
                  
            # Update the value of ans
            ans += (freq[arr[i] - D] *
                    freq[arr[i] - 2 * D])
 
        # Increase the frequency
        # of the current element
        freq[arr[i]] = freq.get(arr[i], 0) + 1
 
    # Return the resultant count
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 4, 5, 7, 8, 10 ]
    D = 1
     
    print (countTriplets(D, arr))
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
static int countTriplets(int D, int[] arr)
{
     
    // Stores the frequency
    // of array elements
    Dictionary<int,
               int> freq = new Dictionary<int,
                                          int>();
 
    // Stores the count of
    // resultant triplets
    int ans = 0;
 
    // Traverse the array
    for(int i = 0; i < arr.Length; i++)
    {
         
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.ContainsKey(arr[i] - D) &&
            freq.ContainsKey(arr[i] - 2 * D))
        {
             
            // Update the value of ans
            ans += freq[arr[i] - D] *
                   freq[arr[i] - 2 * D];
        }
 
        // Increase the frequency
        // of the current element
        if (!freq.ContainsKey(arr[i]))
            freq[arr[i]] = 0;
             
        freq[arr[i]]++;
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 2, 4, 5, 7, 8, 10 };
    int D = 1;
     
    Console.WriteLine(countTriplets(D, arr));
}
}
 
// This code is contributed by ukasp


Javascript




<script>
 
// javascript program for the above approach
 
// Function to count the number of
// triplets having difference
// between adjacent  elements equal to D
function countTriplets(D, arr)
{
    // Stores the frequency
    // of array elements
    var freq = new Map();
   
    // Stores the count of
    // resultant triplets
    var ans = 0;
    var i;
 
    // Traverse the array
    for (i = 0; i < arr.length; i++) {
 
        // Check if arr[i] - D and
        // arr[i] - 2 * D  exists
        // in the Hashmap or not
        if (freq.has(arr[i] - D) && freq.has(arr[i] - 2 * D)) {
 
            // Update the value of ans
            ans += freq.get(arr[i] - D) * freq.get(arr[i] - 2 * D);
        }
 
        // Increase the frequency
        // of the current element
        freq.set(arr[i],freq.get(arr[i])+1);
    }
 
    // Return the resultant count
    return ans;
}
 
// Driver Code
    var arr = [1, 2, 4, 5, 7, 8, 10];
    var D = 1;
    document.write(countTriplets(D, arr));
 
</script>


Output: 

0

 

Time Complexity: O(N) 
Auxiliary Space: O(N)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads