Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j] - GeeksforGeeks

13 Apr, 2021
Given an array arr[] of N integers, the task is to count number of triplets (i, j, k) in the array such that a[k] < a[i] < a[j] and i < j < k.Examples: 
Input: arr[] = {2, 5, 1, 3, 0} Output: 4 Explanation: Below are the triplets (i, j, k) such that i < j < k and a[k] < a[i] < a[j]: 1. (0, 1, 2) and arr[2] < arr[0] 1 < 2 < 5.2. (0, 1, 4) and arr[4] < arr[0] 0 < 2 < 5.3. (0, 3, 4) and arr[4] < arr[0] 0 < 2 < 3.4. (2, 3, 4) and arr[4] < arr[2] 0 < 1 < 3.Input: arr[] = {2, 5, 1, 2, 0, 3, 10, 1, 5, 0 } Output: 25  
Naive Approach: The idea is to iterate 3 loops and check for each triplet (i, j, k) satisfy the given conditions or not. If yes then increment for that triplet and print the final count after checking all the triplets.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count triplets with the// given conditionsint CountTriplets(int arr[], int n){    int cnt = 0;     for (int i = 0; i < n; i++)        for (int j = i + 1; j < n; j++)            for (int k = j + 1; k < n; k++)                 // If it satisfy the                // given conditions                if (arr[k] < arr[i]                    && arr[i] < arr[j]) {                     cnt += 1;                }     // Return the final count    return cnt;} // Driver Codeint main(){    // Given array arr[]    int arr[] = { 2, 5, 1, 3, 0 };     int n = sizeof(arr) / sizeof(arr[0]);     // Function Call    cout << CountTriplets(arr, n)         << endl;    return 0;}
// Java program for the above approachclass GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int arr[], int n){    int cnt = 0;     for(int i = 0; i < n; i++)       for(int j = i + 1; j < n; j++)          for(int k = j + 1; k < n; k++)                           // If it satisfy the             // given conditions             if (arr[k] < arr[i] &&                 arr[i] < arr[j])             {                 cnt += 1;             }                  // Return the final count    return cnt;} // Driver Codepublic static void main(String[] args){         // Given array arr[]    int arr[] = new int[]{ 2, 5, 1, 3, 0 };     int n = arr.length;         System.out.print(CountTriplets(arr, n));}} // This code is contributed by Pratima Pandey
# Python3 program for the above approach # Function to count triplets with the# given conditionsdef CountTriplets(arr, n):     cnt = 0;     for i in range(0, n):        for j in range(i + 1, n):            for k in range(j + 1, n):                 # If it satisfy the                # given conditions                if (arr[k] < arr[i] and arr[i] < arr[j]):                    cnt += 1;                     # Return the final count    return cnt; # Driver Code # Given array arr[]arr = [ 2, 5, 1, 3, 0 ]; n = len(arr); # Function Callprint(CountTriplets(arr, n)) # This code is contributed by Code_Mech
// C# program for the above approachusing System;class GFG{ // Function to count triplets// with the given conditionsstatic int CountTriplets(int []arr, int n){    int cnt = 0;     for(int i = 0; i < n; i++)       for(int j = i + 1; j < n; j++)          for(int k = j + 1; k < n; k++)                           // If it satisfy the             // given conditions             if (arr[k] < arr[i] &&                 arr[i] < arr[j])             {                 cnt += 1;             }                 // Return the final count    return cnt;} // Driver Codepublic static void Main(string[] args){         // Given array arr[]    int []arr = new int[]{ 2, 5, 1, 3, 0 };     int n = arr.Length;         Console.Write(CountTriplets(arr, n));}} // This code is contributed by Ritik Bansal
<script>     // Javascript program for the above approach         // Function to count triplets with the    // given conditions    function CountTriplets(arr, n)    {        let cnt = 0;         for (let i = 0; i < n; i++)            for (let j = i + 1; j < n; j++)                for (let k = j + 1; k < n; k++)                     // If it satisfy the                    // given conditions                    if (arr[k] < arr[i]                        && arr[i] < arr[j]) {                         cnt += 1;                    }         // Return the final count        return cnt;    }         // Given array arr[]    let arr = [ 2, 5, 1, 3, 0 ];      let n = arr.length;      // Function Call    document.write(CountTriplets(arr, n));     </script>
4
 
Time Complexity: O(N3) Auxiliary Space: O(1)
Efficient Approach: We can reduce the complexity from N^3 to N^2, using the below steps:  
Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt.While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k.
Run two loops to find pairs (i, j) such that i < j and arr[j] > arr[i] and keep the count of these pairs as cnt.
While in the above loop if there exists any element such arr[j] < arr[i] then increment the count of triplets by cnt as the current element is the Kth element such that a[k] < a[i] < a[j] for triplet i < j < k.
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count  tripletsint CountTriplets(int a[], int n){     // To store count of total triplets    int ans = 0;     for (int i = 0; i < n; i++) {         // Initialize count to zero        int cnt = 0;         for (int j = i + 1; j < n; j++) {             // If a[j] > a[i] then,            // increment cnt            if (a[j] > a[i])                cnt++;             // If a[j] < a[i], then            // it mean we have found a[k]            // such that a[k] < a[i] < a[j]            else                ans += cnt;        }    }     // Return the final count    return ans;} // Driver codeint main(){    int arr[] = { 2, 5, 1, 3, 0 };     int n = sizeof(arr) / sizeof(arr[0]);     cout << CountTriplets(arr, n) << endl;     return 0;}
// Java program for the above approachclass GFG{ // Function to count tripletsstatic int CountTriplets(int a[], int n){     // To store count of total triplets    int ans = 0;     for (int i = 0; i < n; i++)    {         // Initialize count to zero        int cnt = 0;         for (int j = i + 1; j < n; j++)        {             // If a[j] > a[i] then,            // increment cnt            if (a[j] > a[i])                cnt++;             // If a[j] < a[i], then            // it mean we have found a[k]            // such that a[k] < a[i] < a[j]            else                ans += cnt;        }    }     // Return the final count    return ans;} // Driver codepublic static void main(String[] args){    int arr[] = { 2, 5, 1, 3, 0 };     int n = arr.length;     System.out.print(CountTriplets(arr, n));}} // This code is contributed by shivanisinghss2110
# Python3 program for# the above approach # Function to count  tripletsdef CountTriplets(a, n):     # To store count    # of total triplets    ans = 0     for i in range (n):         # Initialize count to zero        cnt = 0         for j in range (i + 1 , n):             # If a[j] > a[i] then,            # increment cnt            if (a[j] > a[i]):                cnt += 1             # If a[j] < a[i], then            # it mean we have found a[k]            # such that a[k] < a[i] < a[j]            else:                ans += cnt          # Return the final count    return ans # Driver codeif __name__ == "__main__":     arr = [2, 5, 1, 3, 0]    n = len(arr)    print (CountTriplets(arr, n)) # This code is contributed by Chitranayal
// C# program for the above approachusing System;class GFG{ // Function to count tripletsstatic int CountTriplets(int []a, int n){     // To store count of total triplets    int ans = 0;     for (int i = 0; i < n; i++)    {         // Initialize count to zero        int cnt = 0;         for (int j = i + 1; j < n; j++)        {             // If a[j] > a[i] then,            // increment cnt            if (a[j] > a[i])                cnt++;             // If a[j] < a[i], then            // it mean we have found a[k]            // such that a[k] < a[i] < a[j]            else                ans += cnt;        }    }     // Return the final count    return ans;} // Driver codepublic static void Main(){    int []arr = { 2, 5, 1, 3, 0 };     int n = arr.Length;     Console.Write(CountTriplets(arr, n));}} // This code is contributed by Code_Mech
<script> // Javascript program for the above approach // Function to count  tripletsfunction CountTriplets(a, n){         // To store count of total triplets    let ans = 0;     for(let i = 0; i < n; i++)    {                 // Initialize count to zero        let cnt = 0;         for(let j = i + 1; j < n; j++)        {                         // If a[j] > a[i] then,            // increment cnt            if (a[j] > a[i])                cnt++;             // If a[j] < a[i], then            // it mean we have found a[k]            // such that a[k] < a[i] < a[j]            else                ans += cnt;        }    }     // Return the final count    return ans;} // Driver codelet arr = [ 2, 5, 1, 3, 0 ];let n = arr.length; document.write(CountTriplets(arr, n)); // This code is contributed by rameshtravel07 </script>
4
 
Time Complexity: O(N2) Auxiliary Space: O(1)
dewantipandeydp
bansal_rtk_
shivanisinghss2110
Code_Mech
ukasp
divyesh072019
rameshtravel07
Arrays
Competitive Programming
Data Structures
Data Structures
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Bits manipulation (Important tactics)