Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Count of index triplets (i, j, k) in given Array such that i
  • Difficulty Level : Easy
  • Last Updated : 03 Dec, 2021

Given an array arr[], the task is to count the number of triplets such that i < j <k and a[ j ]< a[ k ]< a[ i ]

Examples:

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 experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input:  arr[] = {1, 2, 3, 4, 5}
Output: -1
Explaination: There is no triplets of required type.



Input:  arr[] = {4, 1, 3, 5}
Output: 1
Explaination: There is a  triplet in array a[]: {4, 1, 3 }.

Input:  arr[] = {2, 1, -3, -2, 5}
Output: 2
Explaination: There are  two triplets of required type: {2, 1, -3}, {1, -3, -2}

 

Naive Approach: Use three loops to check for all the possible triplets in a[] and count the number of triplets in arr[] such that i<j<k and a[ j ]< a[ k ]< a[ i ]. Below is the implementation of the above approach.  

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
int findTriplets(int a[], int n)
{
 
    // To count desired triplets
    int cnt = 0;
 
    // Three loops to find triplets
    for (int i = 0; i < n; i++)
    {
        for (int j = i + 1; j < n; j++)
        {
            for (int k = j + 1; k < n; k++)
            {
 
                if (a[j] < a[k] && a[k] < a[i])
                    cnt++;
            }
        }
    }
 
    // Return the number of triplets found
    return cnt;
}
 
// Driver code
int main()
{
    int a[] = {2, 1, -3, -2, 5};
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << (findTriplets(a, n));
    return 0;
}
 
// This code is contributed by Potta Lokesh

Java




// Java Program for above approach
import java.io.*;
 
class GFG {
 
    public static int findTriplets(int[] a)
    {
 
        // To count desired triplets
        int cnt = 0;
 
        // Three loops to find triplets
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                for (int k = j + 1; k < a.length; k++) {
 
                    if (a[j] < a[k] && a[k] < a[i])
                        cnt++;
                }
            }
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 2, 1, -3, -2, 5 };
 
        System.out.println(findTriplets(a));
    }
}

Python3




# Python Program for above approach
def findTriplets(a):
 
  # To count desired triplets
  cnt = 0;
 
  # Three loops to find triplets
  for i in range(len(a)):
    for j in range(i + 1, len(a)):
      for k in range(j + 1, len(a)):
        if (a[j] < a[k] and a[k] < a[i]):
          cnt += 1
 
  # Return the number of triplets found
  return cnt;
 
# Driver code
a = [2, 1, -3, -2, 5];
print(findTriplets(a));
 
# This code is contributed by Saurabh Jaiswal

C#




// C# Program for above approach
using System;
public class GFG {
 
  public static int findTriplets(int[] a)
  {
 
    // To count desired triplets
    int cnt = 0;
 
    // Three loops to find triplets
    for (int i = 0; i < a.Length; i++) {
      for (int j = i + 1; j < a.Length; j++) {
        for (int k = j + 1; k < a.Length; k++) {
 
          if (a[j] < a[k] && a[k] < a[i])
            cnt++;
        }
      }
    }
 
    // Return the number of triplets found
    return cnt;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int []a = { 2, 1, -3, -2, 5 };
 
    Console.WriteLine(findTriplets(a));
  }
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
// Javascript Program for above approach
function findTriplets(a) {
 
  // To count desired triplets
  let cnt = 0;
 
  // Three loops to find triplets
  for (let i = 0; i < a.length; i++) {
    for (let j = i + 1; j < a.length; j++) {
      for (let k = j + 1; k < a.length; k++) {
 
        if (a[j] < a[k] && a[k] < a[i])
          cnt++;
      }
    }
  }
 
  // Return the number of triplets found
  return cnt;
}
 
// Driver code
 
let a = [2, 1, -3, -2, 5];
 
document.write(findTriplets(a));
 
// This code is contributed by gfgking.
</script>
Output
2

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

Efficient Approach: A Stack can be used to optimize the above solution. The stack will keep track of the next smaller and second smaller element on the right side. 

Follow the steps below to solve the given problem. 

  • Create a stack and variable say secondMin = INT_MAX.
  • Declare a variable say cnt = 0, to store the number of desired triplets.
  • Start traversing from the end of the array a[].
    • Check if the current element is greater than the secondMin, if it is that means, the required triplet is found because the stack is keeping track of the next smaller and second smaller elements and the current element satisfies the type. Then, set cnt = cnt + 1.
    • If the above condition is not satisfied, update the minimum value in the stack, keep popping until stack is not empty or the current element is not smaller than the top of the stack.
    • Push current element in the stack
  • At last return cnt as the number of triplets found.

Below is the implementation of the above approach:

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find desired triplets
int findTriplets(vector<int>& a)
{
 
    // To store the number of triplets found
    int cnt = 0;
 
    stack<int> st;
 
    // Keep track of second minimum element
    int secondMin = INT_MAX;
 
    for (int i = a.size() - 1; i >= 0; i--) {
 
        // If required triplet is found
        if (a[i] > secondMin)
            cnt++;
 
        while (!st.empty() && st.top() > a[i]) {
 
            secondMin = st.top();
            st.pop();
        }
        st.push(a[i]);
    }
   
    // Return the number of triplets found
    return cnt;
}
 
// Driver code
int main()
{
    vector<int> a = { 2, 1, -3, -2, 5 };
 
    // Print the required result
    cout << findTriplets(a);
    return 0;
}
 
    // This code is contributed by rakeshsahni

Java




// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find desired triplets
    public static int findTriplets(int[] a)
    {
 
        // To store the number of triplets found
        int cnt = 0;
 
        Stack<Integer> stack = new Stack<>();
 
        // Keep track of second minimum element
        int secondMin = Integer.MAX_VALUE;
 
        for (int i = a.length - 1; i >= 0; i--) {
 
            // If required triplet is found
            if (a[i] > secondMin)
                cnt++;
 
            while (!stack.isEmpty()
                   && stack.peek() > a[i]) {
 
                secondMin = stack.pop();
            }
            stack.push(a[i]);
        }
 
        // Return the number of triplets found
        return cnt;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int a[] = { 2, 1, -3, -2, 5 };
 
        // Print the required result
        System.out.println(findTriplets(a));
    }
}
Output
2

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




My Personal Notes arrow_drop_up

Recommended Articles
Page :

Start Your Coding Journey Now!