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

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →