Naveen Verma
Naveen Verma

Reputation: 49

in Valid Anagram program not passing all test cases

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram" Output: true Example 2:

Input: s = "rat", t = "car" Output: false

example 3 "aad" "cab" Output true Expected false

my 3 test case is giving output true why?

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.isEmpty() && t.isEmpty()) {
            return true;
        }
        if (s.length() != t.length()) {
            return false;
        }
        char[] a = s.toCharArray();
        char[] b = t.toCharArray();

        Arrays.sort(a);
        Arrays.sort(b);
        for (int i = 0; i <= a.length; i++) {
            for (int j = 0; j <= b.length; j++) {
                if (a[i] == b[j]) {
                    return true;    
                }
            }
        }
        return false;
    }
}

Upvotes: 1

Views: 259

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

By using a nested for loop, you will iterate over every possible pair (i, j) with i and j an in idex in a and b respectively. Furthermore you use i++ and j++ twice, and thus you will skip the even indices. You can not return true from the moment a[i++] == b[j++] matches. In order to know if something is an anagram, you need to iterate over all elements. You can return false from the moment a[i] != b[i] however. Finally the bound should be i < a.length, not i <= a.length.

You thus need one for loop where you make a single increment and compare a[i] with b[i]:

public boolean isAnagram(String s, String t) {
    if(s.length() != t.length()){
        return false;
    }
    char[] a = s.toCharArray();
    char[] b = t.toCharArray();

    Arrays.sort(a);
    Arrays.sort(b);

    for(int i = 0; i < a.length; i++) {
        if(a[i] != b[i]) {
            return false;
        }
    }
    return true;
}

Upvotes: 1

Jaikanth J
Jaikanth J

Reputation: 592

You are just comparing the first letter of cab and rat which is a, and returning True, actually you need to check all letters.

Hence make the condition negative and swap the returns.

 if(a[i++] !=b[j++]){
   return false;
  } 
return true; 

The above code will return false, when characters aren’t equal, hence the last line is reached only when all chars are equal.

Upvotes: 0

Related Questions