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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

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...