Open In App

Count of ordered triplets with indices (i, j, k) representing distinct values and j – i != k – j

Improve
Improve
Like Article
Like
Save
Share
Report

Given a ternary string S consisting of only three characters, the task is to find the count of ordered triplets (i, j, k) such that S[i], S[j] and S[k] are distinct and j – i != k – j.

Example:

Input: str = “AABC”
Output: 1
Explanation: Only the triplet (0, 2, 3) satisfies the required conditions as S[0], S[2], and S[3] are distinct and 2 – 0 != 3 – 2. The triplet (1, 2, 3) also represents all distinct characters but 2 – 1 = 3 – 2 violating the 2nd condition.

Input: str = “PQRRPQQR”
Output: 13

 

Approach: The given problem can be solved by dividing the problem into two parts. The idea is to calculate the count of triples with distinct characters and then subtract the triplets such that they have distinct characters and j – i = k – j. Below are the steps to calculate both:

  • The total count of triplets with distinct characters can be calculated by calculating the frequency of three characters suppose X, Y, Z. Hence, the all possible pairs will be XC1 * YC1 * ZC1 => X * Y * Z, i.e, the product of their frequencies.
  • It can be observed that the equation k – j = j – i can be converted to k = 2*j – i. Hence, iterate over all possible values of (i, j) and calculate the value of k. If the indices (i, j, k) represents the distinct characters, increment the count.
  • The required answer will therefore be the difference of the values calculated in the above steps.

Below is the implementation of the above approach:

C++




// C++ Program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find count of triplets
// with indices (i, j, k) representing
// distinct values and j - i != k - j
int cntTriplets(string S, int N)
{
    // Stores the frequency of
    // characters in string
    unordered_map<char, int> freq;
 
    for (int i = 0; i < N; i++) {
        freq[S[i]]++;
    }
 
    // Stores the product
    // of frequencies
    int prod = 1;
 
    for (auto x : freq) {
        prod *= x.second;
    }
 
    // If string has less than
    // three distinct characters
    if (freq.size() < 3) {
        prod = 0;
    }
 
    // Stores the triplets
    // with j-i = k-j
    int cnt = 0;
 
    // Loop to iterate over all
    // ordered pairs of (i, j)
    for (int i = 0; i < N; i++) {
        for (int j = i + 1; j < N; j++) {
 
            // Calculate K
            int k = 2 * j - i;
 
            // If k is out of bound
            if (k >= N)
                break;
 
            // If S[i], S[j] and
            // S[k] are unique
            if (S[i] != S[j] && S[j] != S[k]
                && S[i] != S[k])
                cnt++;
        }
    }
    return prod - cnt;
}
 
// Driver Code
int main()
{
    string S = "PQRRPQQR";
    cout << cntTriplets(S, S.length());
 
    return 0;
}


Java




// Java program for the given approach
import java.util.HashMap;
class GFG {
 
  // Function to find count of triplets
  // with indices (i, j, k) representing
  // distinct values and j - i != k - j
  static int cntTriplets(String S, int N) {
 
    // Stores the frequency of
    // characters in String
    HashMap<Character, Integer> freq = new HashMap<Character, Integer>();
 
    for (int i = 0; i < N; i++) {
      if (freq.containsKey(S.charAt(i))) {
        freq.put(S.charAt(i), freq.get(S.charAt(i)) + 1);
      } else {
        freq.put(S.charAt(i), 1);
      }
    }
 
    // Stores the product
    // of frequencies
    int prod = 1;
 
    for (char x : freq.keySet()) {
      prod *= freq.get(x);
    }
 
    // If String has less than
    // three distinct characters
    if (freq.size() < 3) {
      prod = 0;
    }
 
    // Stores the triplets
    // with j-i = k-j
    int cnt = 0;
 
    // Loop to iterate over all
    // ordered pairs of (i, j)
    for (int i = 0; i < N; i++) {
      for (int j = i + 1; j < N; j++) {
 
        // Calculate K
        int k = 2 * j - i;
 
        // If k is out of bound
        if (k >= N)
          break;
 
        // If S[i], S.charAt(j) and
        // S.charAt(k) are unique
        if (S.charAt(i) != S.charAt(j) && S.charAt(j) != S.charAt(k)
            && S.charAt(i) != S.charAt(k))
          cnt++;
      }
    }
    return prod - cnt;
  }
 
  // Driver code
  public static void main(String args[]) {
 
    String S = "PQRRPQQR";
 
    System.out.println(cntTriplets(S, S.length()));
  }
}
 
// This code is contributed by gfgking


Python3




# Python 3 Program of the above approach
from collections import defaultdict
 
# Function to find count of triplets
# with indices (i, j, k) representing
# distinct values and j - i != k - j
def cntTriplets(S, N):
 
    # Stores the frequency of
    # characters in string
    freq = defaultdict(int)
 
    for i in range(N):
        freq[S[i]] += 1
 
    # Stores the product
    # of frequencies
    prod = 1
 
    for x in freq:
        prod *= freq[x]
 
    # If string has less than
    # three distinct characters
    if (len(freq) < 3):
        prod = 0
 
    # Stores the triplets
    # with j-i = k-j
    cnt = 0
 
    # Loop to iterate over all
    # ordered pairs of (i, j)
    for i in range(N):
        for j in range(i + 1,  N):
 
            # Calculate K
            k = 2 * j - i
 
            # If k is out of bound
            if (k >= N):
                break
 
            # If S[i], S[j] and
            # S[k] are unique
            if (S[i] != S[j] and S[j] != S[k]
                    and S[i] != S[k]):
                cnt += 1
 
    return prod - cnt
 
# Driver Code
if __name__ == "__main__":
 
    S = "PQRRPQQR"
    print(cntTriplets(S, len(S)))
 
    # This code is contributed by ukasp.


C#




// C# program for the given approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to find count of triplets
  // with indices (i, j, k) representing
  // distinct values and j - i != k - j
  static int cntTriplets(string S, int N)
  {
     
    // Stores the frequency of
    // characters in string
    Dictionary<char, int> freq =
      new Dictionary<char, int>();
 
    for (int i = 0; i < N; i++) {
      if (freq.ContainsKey(S[i]))
      {
        freq[S[i]] = freq[S[i]] + 1;
      }
      else
      {
        freq.Add(S[i], 1);
      }
    }
 
    // Stores the product
    // of frequencies
    int prod = 1;
 
    foreach(KeyValuePair<char, int> x in freq)
    {
      prod *= x.Value;
    }
 
    // If string has less than
    // three distinct characters
    if (freq.Count < 3) {
      prod = 0;
    }
 
    // Stores the triplets
    // with j-i = k-j
    int cnt = 0;
 
    // Loop to iterate over all
    // ordered pairs of (i, j)
    for (int i = 0; i < N; i++) {
      for (int j = i + 1; j < N; j++) {
 
        // Calculate K
        int k = 2 * j - i;
 
        // If k is out of bound
        if (k >= N)
          break;
 
        // If S[i], S[j] and
        // S[k] are unique
        if (S[i] != S[j] && S[j] != S[k]
            && S[i] != S[k])
          cnt++;
      }
    }
    return prod - cnt;
  }
 
  // Driver code
  public static void Main()
  {
 
    string S = "PQRRPQQR";
 
    Console.Write(cntTriplets(S, S.Length));
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find count of triplets
       // with indices (i, j, k) representing
       // distinct values and j - i != k - j
       function cntTriplets(S, N)
       {
        
           // Stores the frequency of
           // characters in string
           let freq = new Map();
 
           for (let i = 0; i < N; i++) {
               if (freq.has(S[i]))
                   freq.set(S[i], freq.get(S[i]) + 1);
               else
                   freq.set(S[i], 1)
           }
 
           // Stores the product
           // of frequencies
           let prod = 1;
 
           for (let [key, x] of freq) {
               prod *= x;
           }
 
           // If string has less than
           // three distinct characters
           if (freq.size < 3) {
               prod = 0;
           }
 
           // Stores the triplets
           // with j-i = k-j
           let cnt = 0;
 
           // Loop to iterate over all
           // ordered pairs of (i, j)
           for (let i = 0; i < N; i++) {
               for (let j = i + 1; j < N; j++) {
 
                   // Calculate K
                   let k = 2 * j - i;
 
                   // If k is out of bound
                   if (k >= N)
                       break;
 
                   // If S[i], S[j] and
                   // S[k] are unique
                   if (S[i] != S[j] && S[j] != S[k]
                       && S[i] != S[k])
                       cnt++;
               }
           }
           return prod - cnt;
       }
 
       // Driver Code
       let S = "PQRRPQQR";
       document.write(cntTriplets(S, S.length));
 
      // This code is contributed by Potta Lokesh
   </script>


 
 

Output

13

 

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

 



Last Updated : 24 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads