Open In App

Count non-equidistant triplets of distinct array elements having indices in increasing order

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N consisting of only 0s, 1s and 2s, the task is to find the count of triplets of indices (i, j, k) containing distinct array elements such that i < j < k and the array elements are not equidistant, i.e, (j – i )!= (k – j).

Examples:

Input: arr[] = { 0, 1, 2, 1 } 
Output:
Explanation: 
Only triplet (0, 2, 3) contains distinct array elements and (2 – 0) != (3 – 2). 
Therefore, the required output is 1.

Input: arr[] = { 0, 1, 2 } 
Output:
Explanation: 
No triplet exists that satisfy the condition. 
Therefore, the required output is 0.

Approach: The idea is to store the indices of array elements 0s, 1s and 2s in three separate arrays, then find the count triplets that satisfy the given conditions. Follow the steps below to solve the problem:

  • Initialize two arrays, say zero_i[] and one_i[], to store the indices of 0s and 1s from the given array respectively.
  • Initialize a map, say mp, to store the indices of 2s from the given array.
  • Find the total count of all possible triplets by multiplying the size of zero_i[], one_i[] and mp.
  • Now, subtract all those triplets which violate the given conditions.
  • For finding such triplets, traverse both the arrays zero_i[] and one_i[] and try to find a third index in the Map that violates the condition.
  • To find the third index which violates the conditions, following three cases arise: 
    1. The third index is equidistant from both the indices and is present in between them.
    2. The third index is equidistant from both the indices and is present on the left side of the first index.
    3. The third index is equidistant from both the indices and is present on the right side of the second index.
  • Remove all such triplets from the count of the total number of triplets.
  • Finally, print the total count of triplets obtained.

Below is the implementation of the above approach:

C++14




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
int countTriplets(int* arr, int N)
{
 
    // Stores indices of 0s
    vector<int> zero_i;
 
    // Stores indices of 1s
    vector<int> one_i;
 
    // Stores indices of 2s
    unordered_map<int, int> mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.push_back(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.push_back(i + 1);
 
        // If current array element
        // is 2
        else
            mp[i + 1] = 1;
    }
 
    // Total count of triplets
    int total = zero_i.size()
                * one_i.size() * mp.size();
 
    // Traverse  the array zero_i[]
    for (int i = 0; i < zero_i.size();
         i++) {
 
        // Traverse the array one_i[]
        for (int j = 0; j < one_i.size();
             j++) {
 
            // Stores index of 0s
            int p = zero_i[i];
 
            // Stores index of 1s
            int q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp[r] > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp[r] > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp[r] > 0 && abs(r - p) == abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    cout << total;
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 2, 1 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countTriplets(arr, N);
 
    return 0;
}


Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
static void countTriplets(int []arr, int N)
{
     
    // Stores indices of 0s
    Vector<Integer> zero_i = new Vector<Integer>();
 
    // Stores indices of 1s
    Vector<Integer> one_i = new Vector<Integer>();
 
    // Stores indices of 2s
    HashMap<Integer,
            Integer> mp = new HashMap<Integer,
                                      Integer>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.add(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.add(i + 1);
 
        // If current array element
        // is 2
        else
            mp.put(i + 1, 1);
    }
 
    // Total count of triplets
    int total = zero_i.size() *
                 one_i.size() * mp.size();
 
    // Traverse  the array zero_i[]
    for(int i = 0; i < zero_i.size(); i++)
    {
         
        // Traverse the array one_i[]
        for(int j = 0; j < one_i.size(); j++)
        {
             
            // Stores index of 0s
            int p = zero_i.get(i);
 
            // Stores index of 1s
            int q = one_i.get(j);
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.containsKey(r) && mp.get(r) > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.containsKey(r) && mp.get(r) > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.containsKey(r) &&
                    mp.get(r) > 0 &&
                  Math.abs(r - p) == Math.abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    System.out.print(total);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 0, 1, 2, 1 };
    int N = arr.length;
 
    countTriplets(arr, N);
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program to implement
# the above approach
 
# Function to find the total count of
# triplets (i, j, k) such that i < j < k
# and (j - i) != (k - j)
def countTriplets(arr, N):
 
    # Stores indices of 0s
    zero_i = []
 
    # Stores indices of 1s
    one_i = []
 
    # Stores indices of 2s
    mp = {}
 
    # Traverse the array
    for i in range(N):
 
        # If current array element
        # is 0
        if (arr[i] == 0):
            zero_i.append(i + 1)
 
        # If current array element is 1
        elif (arr[i] == 1):
            one_i.append(i + 1)
 
        # If current array element
        # is 2
        else:
            mp[i + 1] = 1
 
    # Total count of triplets
    total = len(zero_i) * len(one_i) * len(mp)
 
    # Traverse  the array zero_i[]
    for i in range(len(zero_i)):
 
        # Traverse the array one_i[]
        for j in range(len(one_i)):
 
            # Stores index of 0s
            p = zero_i[i]
 
            # Stores index of 1s
            q = one_i[j]
 
            # Stores third element of
            # triplets that does not
            # satisfy the condition
            r = 2 * p - q
 
            # If r present
            # in the map
            if (r in mp):
                total -= 1
 
            # Update r
            r = 2 * q - p
 
            # If r present
            # in the map
            if (r in mp):
                total -= 1
 
            # Update r
            r = (p + q) // 2
 
            # If r present in the map
            # and equidistant
            if ((r in mp) and abs(r - p) == abs(r - q)):
                total -= 1
 
    # Print the obtained count
    print (total)
 
# Driver Code
if __name__ == '__main__':
    arr = [0, 1, 2, 1]
    N = len(arr)
    countTriplets(arr, N)
 
    # This code is contributed by mohit kumar 29


C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
static void countTriplets(int []arr, int N)
{
     
    // Stores indices of 0s
    List<int> zero_i = new List<int>();
 
    // Stores indices of 1s
    List<int> one_i = new List<int>();
 
    // Stores indices of 2s
    Dictionary<int,
            int> mp = new Dictionary<int,
                                      int>();
 
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.Add(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.Add(i + 1);
 
        // If current array element
        // is 2
        else
            mp.Add(i + 1, 1);
    }
 
    // Total count of triplets
    int total = zero_i.Count *
                 one_i.Count * mp.Count;
 
    // Traverse  the array zero_i[]
    for(int i = 0; i < zero_i.Count; i++)
    {
         
        // Traverse the array one_i[]
        for(int j = 0; j < one_i.Count; j++)
        {
             
            // Stores index of 0s
            int p = zero_i[i];
 
            // Stores index of 1s
            int q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            int r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.ContainsKey(r) && mp[r] > 0)
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.ContainsKey(r) && mp[r] > 0)
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.ContainsKey(r) &&
                    mp[r] > 0 &&
                  Math.Abs(r - p) == Math.Abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    Console.Write(total);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 0, 1, 2, 1 };
    int N = arr.Length;
    countTriplets(arr, N);
}
}
 
// This code contributed by shikhasingrajput


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Function to find the total count of
// triplets (i, j, k) such that i < j < k
// and (j - i) != (k - j)
function countTriplets(arr, N)
{
 
    // Stores indices of 0s
    var zero_i = [];
 
    // Stores indices of 1s
    var one_i = [];
 
    // Stores indices of 2s
    var mp = new Map();
 
    // Traverse the array
    for (var i = 0; i < N; i++) {
 
        // If current array element
        // is 0
        if (arr[i] == 0)
            zero_i.push(i + 1);
 
        // If current array element is 1
        else if (arr[i] == 1)
            one_i.push(i + 1);
 
        // If current array element
        // is 2
        else
            mp.set(i + 1, 1);
    }
 
    // Total count of triplets
    var total = zero_i.length
                * one_i.length * mp.size;
 
    // Traverse  the array zero_i[]
    for (var i = 0; i < zero_i.length;
         i++) {
 
        // Traverse the array one_i[]
        for (var j = 0; j < one_i.length;
             j++) {
 
            // Stores index of 0s
            var p = zero_i[i];
 
            // Stores index of 1s
            var q = one_i[j];
 
            // Stores third element of
            // triplets that does not
            // satisfy the condition
            var r = 2 * p - q;
 
            // If r present
            // in the map
            if (mp.has(r))
                total--;
 
            // Update r
            r = 2 * q - p;
 
            // If r present
            // in the map
            if (mp.has(r))
                total--;
 
            // Update r
            r = (p + q) / 2;
 
            // If r present in the map
            // and equidistant
            if (mp.has(r) && Math.abs(r - p) == Math.abs(r - q))
                total--;
        }
    }
 
    // Print the obtained count
    document.write( total);
}
 
// Driver Code
var arr = [0, 1, 2, 1];
var N = arr.length;
countTriplets(arr, N);
 
 
</script>


Output: 

1

 

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



Last Updated : 14 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads