Sherlock and Anagrams


Problem Statement :


Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.

For example s = mom , the list of all anagrammatic pairs is [m,m], [mo, om] at positions [ [1], [2], [0,1], [1,2] ] respectively .

Function Description

Complete the function sherlockAndAnagrams in the editor below. It must return an integer that represents the number of anagrammatic pairs of substrings in s.

sherlockAndAnagrams has the following parameter(s)
     s: a string .

Input Format

The first line contains an integer q , the number of queries .
Each of the next  q lines contains a string s to analyze.

Constraints
  
   1 <= q <= 10
   2 <= | s| <= 100


Output Format

For each query, return the number of unordered anagrammatic pairs.



Solution :



title-img


                            Solution in C :

In C :


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

typedef struct node{
    int s;
    int e;
}node;

void combine(node *A,int start,int end,int index,int *sum,node *temp,char *str){
    
    if(index == 2){
        int m[26] = {0};
        int i;
        for(i=temp[0].s;i<=temp[0].e;i++)
            m[str[i] - 'a']++;
        
        for(i=temp[1].s;i<=temp[1].e;i++)
            m[str[i] - 'a']--;
        
        for(i=0;i<26;i++)
            if(m[i])
                return;
            
        *sum += 1;
        return;
    }
    
    int i;
    
    for(i=start;i<end;i++){
        temp[index] = A[i];
        combine(A,i+1,end,index+1,sum,temp,str);
    }
    
}

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int t;
    scanf("%d",&t);
    
    while(t--){
        char *str = (char*)malloc(sizeof(char)*101);
        scanf("%s",str);
        
        node *A = (node*)malloc(sizeof(node)*100);
        
        int index = 0;
        
        int i;
        int len = strlen(str);
        
        int count;
        int sum = 0;
        
        while(index<len){
            count = 0;
            for(i=0;i<len;i++){
                A[i].s = i;
                if(i+index>=len)
                    break;
                A[i].e = i+index;
                count++;
            }
            
            if(count>=2){
                node *temp = (node*)malloc(sizeof(node)*2);
                combine(A,0,count,0,&sum,temp,str);
            }
            index++;
        }
        
        printf("%d\n",sum);
        
    }
    return 0;
}
                        


                        Solution in C++ :

In C ++ :

#include<bits/stdc++.h>
#include <cstdio>
#define MAX 5000
using namespace std;
map<string,int> mp ;
int main(){
	ios::sync_with_stdio(0);
	int t;
	cin>>t;
	while(t--){
		mp.clear();
		string s,sn,ss ;
		int j;
		cin>>s;
		int l=s.length();
		for(int k=0;k<l;k++){
			ss = "";
			for(int i=0;i<l-k;i++){	
					j = k+i;
					ss = ss + s[j];
					sn = ss ;
					sort(sn.begin() , sn.end());
					mp[sn]++;
			}
		}
		long long int ans = 0 ;
		map<string,int> :: iterator it ;
		for(it = mp.begin() ; it != mp.end() ; it++){
			long long  vl = (long long)(it->second) ;
			if(vl > 1){				
				ans += (vl*(vl-1))/2LL ;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}
                    


                        Solution in Java :

In Java :


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    
    private static int count[][] = new int[128][110];

    private static void resetCount() {
        for (int i = 0; i < count.length; i++) for (int j = 0; j < count[i].length; j++) count[i][j] = 0;
    }
    
    private static boolean areAnagrams(int from1, int to1, int from2, int to2) {
        for (int i = 'a'; i <= 'z'; i++) {
            if (count[i][to1+1]-count[i][from1] != count[i][to2+1]-count[i][from2])
                return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        final Scanner sc = new Scanner(System.in);
        final int TC = Integer.parseInt(sc.nextLine());
        for (int tc = 0; tc < TC; tc++) {
            final char s[] = sc.nextLine().toCharArray();
            resetCount();
            count[s[0]][1] = 1;
            for (int i = 1; i < s.length; i++) {
                for (int j = 'a'; j <= 'z'; j++) count[j][i+1] = count[j][i];
                count[s[i]][i+1]++;
            }
            int res = 0;
            for (int len = 1; len <= s.length-1; len++) {
                for (int from = 0; from <= s.length-len; from++) {
                    for (int to = from+1; to <= s.length-len; to++) {
                        if (areAnagrams(from, from+len-1, to, to+len-1)) res++;
                    }
                }
            }
            System.out.println(res);
        }
    }
}
                    


                        Solution in Python : 
                            
In Python3 :


for _ in range(int(input())):
    was = dict()
    s = input()

    n = len(s)
    for i in range(n):
        for j in range(i, n):
            cur = s[i:j + 1]
            cur = ''.join(sorted(cur))
            was[cur] = was.get(cur, 0) + 1

    ans = 0
    for x in was:
        v = was[x]
        ans += (v * (v - 1)) // 2

    print(ans)
                    


View More Similar Problems

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →