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<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;
}




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);
        }
    }
}




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;
}





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

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 →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →