Skip to content
Advertisement

Output error when comparing anagrams strings

I was solving an anagram question on geek for geeks but I think the output format is not similar as shown in question over all my code is correct but there is a problem in test cases so see my code and tell me what’s wrong in this.

/*package whatever //do not write package name here */
    
import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        sc.nextLine();
        boolean isAnagram = true;
        while (t-- > 0) {
            String a = sc.nextLine();
            String b = sc.nextLine();

            int al[] = new int[256];
            for (char c : a.toCharArray()) {
                int index = (int) c;
                al[index]++;
            }
            for (char c : b.toCharArray()) {
                int index = (int) c;
                al[index]--;
            }
            for (int i = 0; i < 256; i++) {
                if (al[i] != 0) {
                    isAnagram = false;
                    break;
                }
            }

            if (isAnagram) {
                System.out.println("1");
            } else {
                System.out.println("0");
            }
        }
    }
}

This is the output of custom case:

custom case 1

custom case 2

Advertisement

Answer

You need to move boolean isAnagram = true; inside while (t-- > 0) loop.

Currently, if in the first test the text is not an anagram, existing code does not set isAnagram to true.

Also, the two input strings cannot be anagrams if their lengths are different, and explicit casting of char to int is redundant.

That being said, the contents of the while loop should be updated as follows:

while (t-- > 0) {
    String a = sc.nextLine();
    String b = sc.nextLine();

    boolean isAnagram = a.length() == b.length();
    if (isAnagram) {
        int al[] = new int[256];
        for (int c : a.toCharArray()) {
            al[c]++;
        }

        for (int c : b.toCharArray()) {
            al[c]--;
        }

        for (int i = 0; i < al.length; i++) {
            if (al[i] != 0) {
                isAnagram = false;
                break;
            }
        }
    }
    System.out.println(isAnagram ? 1 : 0);
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement