Skip to main content

Sherlock and Anagrams HackerRank solution in Java | Anagrams string in Java

Java solution for Sherlock and Anagrams Problem

Sherlock and Anagrams HackerRank Solution in  Java

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. 

Example 1 :

Input:

s = abba

Output :

4
The list of all anagrammatic pairs is [a, a], [ab, ba], [b, b] and [abb, bba] at positions [[0], [3]], [[0, 1], [2, 3]], [[1], [2]], [[0, 1, 2], [1, 2, 3]].

Example 2 :

s = abcd

No anagrammatic pairs exist in the second query as no character repeats.

In this problem, we have to find that given String is anagram or not. But we have to find in sub string. So lets see solution and its explanation.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.Map.Entry;

class Result {

    public static int sherlockAndAnagrams(String s) {
        int pair = 0;
        Map<String, Integer> map = new HashMap<>();
        int currentPair = 1;
       
        while (currentPair != s.length()) {
            
            for (int i = 0; i < s.length(); i++) {
                
                if (( i+currentPair) <= s.length()) {
                    String subString = s.substring(i, i+currentPair);
                    char[] array = subString.toCharArray();
                    Arrays.sort(array);
                    String sorted = String.valueOf(array);
                    
                    if (map.containsKey(sorted)) {
                        map.put(sorted, map.get(sorted)+1);
                    } else {
                        map.put(sorted, 1);
                    }
                }
                
            }
            currentPair++;
        }
        
        for (Entry<String, Integer> data : map.entrySet()) {
            pair += data.getValue()*(data.getValue()-1) / 2;
        }
        return pair;
    }


}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int q = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, q).forEach(qItr -> {
            try {
                String s = bufferedReader.readLine();

                int result = Result.sherlockAndAnagrams(s);

                bufferedWriter.write(String.valueOf(result));
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Solution Explanation :

  • For solving this problem, we have to create pair of string from 1 to string length -1. ex, String = java so we have to create following pair and check if anagram is applicable or not.
    • pair of 1 character : [j, a], [j, v], [j, a], [a, v], [a, a], [v, a]
    • pair of 2 characters : [ja, av], [ja, va], [av, va]
    • pair of 3 characters : [jav, ava]  
  • Declare and Initialize HashMap<String, Integer>, So we can count pair. Declare two int variable pair and currentPair, initialize with 0 and 1.
  • Using while loop, we create pair of Characters until string length.
  • Traverse through 0 to string length.
    • Write if condition for checking our pair not cause StringIndexOutOfBoundsException.
      • Now we have getting our pair (substring).
      • Convert substring into character array, and sort character array, and then convert character array to String again.
      • Now check if map contains our pair (substring), then increment map value by 1 otherwise pair as new key and value as 1.
  • After completing put all pair in map, Loop through map and apply following formula for getting total pair.
  • pair += data.getValue()*(data.getValue()-1) / 2; 
  • Return pair.


Happy Coding. Happy Learning.

Other Hackerrank solutions in Java :

Comments

Popular posts from this blog

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...