Count number of equal pairs in a string - GeeksforGeeks

31 Dec, 2019
Given a string s, find the number of pairs of characters that are same. Pairs (s[i], s[j]), (s[j], s[i]), (s[i], s[i]), (s[j], s[j]) should be considered different.
Examples :
Input: air
Output: 3
Explanation :
3 pairs that are equal are (a, a), (i, i) and (r, r)

Input : geeksforgeeks
Output : 31

The naive approach will be you to run two nested for loops and find out all pairs and keep a count of all pairs. But this is not efficient enough for longer length of strings.
For an efficient approach, we need to count the number of equal pairs in linear time. Since pairs (x, y) and pairs (y, x) are considered different. We need to use a hash table to store the count of all occurrences of a character.So we know if a character occurs twice, then it will have 4 pairs – (i, i), (j, j), (i, j), (j, i). So using a hash function, store the occurrence of each character, then for each character the number of pairs will be occurrence^2. Hash table will be 256 in length as we have 256 characters.
Below is the implementation of the above approach :
C++
Java
Python 3
C#
// CPP program to count the number of pairs#include <bits/stdc++.h>using namespace std;#define MAX 256  // Function to count the number of equal pairsint countPairs(string s){    // Hash table    int cnt[MAX] = { 0 };      // Traverse the string and count occurrence    for (int i = 0; i < s.length(); i++)        cnt[s[i]]++;      // Stores the answer    int ans = 0;      // Traverse and check the occurrence of every character    for (int i = 0; i < MAX; i++)        ans += cnt[i] * cnt[i];      return ans;}  // Driver Codeint main(){    string s = "geeksforgeeks";    cout << countPairs(s);    return 0;}
// Java program to count the number of pairsimport java.io.*;  class GFG {      static int MAX = 256;          // Function to count the number of equal pairs    static int countPairs(String s)    {        // Hash table        int cnt[] = new int[MAX];              // Traverse the string and count occurrence        for (int i = 0; i < s.length(); i++)            cnt[s.charAt(i)]++;              // Stores the answer        int ans = 0;              // Traverse and check the occurrence        // of every character        for (int i = 0; i < MAX; i++)            ans += cnt[i] * cnt[i];              return ans;    }          // Driver Code    public static void main (String[] args)    {        String s = "geeksforgeeks";        System.out.println(countPairs(s));    }}  // This code is contributed by vt_m
# Python3 program to count the # number of pairs MAX = 256  # Function to count the number # of equal pairsdef countPairs(s):          # Hash table     cnt = [0 for i in range(0, MAX)]      # Traverse the string and count     # occurrence     for i in range(len(s)):        cnt[ord(s[i]) - 97] += 1      # Stores the answer     ans = 0      # Traverse and check the occurrence     # of every character     for i in range(0, MAX):        ans += cnt[i] * cnt[i]      return ans  # Driver code if __name__=="__main__":    s = "geeksforgeeks"    print(countPairs(s))  # This code is contributed # by Sairahul099         
// C# program to count the number of pairsusing System;  class GFG {      static int MAX = 256;          // Function to count the number of equal pairs    static int countPairs(string s)    {        // Hash table        int []cnt = new int[MAX];              // Traverse the string and count occurrence        for (int i = 0; i < s.Length; i++)            cnt[s[i]]++;              // Stores the answer        int ans = 0;              // Traverse and check the occurrence        // of every character        for (int i = 0; i < MAX; i++)            ans += cnt[i] * cnt[i];              return ans;    }          // Driver Code    public static void Main ()    {        string s = "geeksforgeeks";        Console.WriteLine(countPairs(s));    }}  // This code is contributed by vt_m
31

Sairahul Jella
nidhi_biet
frequency-counting
Combinatorial
Strings
Strings
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Print all subsets of given size of a set
Make all combinations of size k
Python program to get all subsets of given size of a set
Count Derangements (Permutation such that no element appears in its original position)
Combinations with repetitions
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
Longest Common Subsequence | DP-4
Different methods to reverse a string in C/C++