egoldman
egoldman

Reputation: 1

Leetcode 242- Valid Anagram: Why is my code failing this test case?

Here's the prompt: Given two strings s and t, return true if t is an anagram of s, and false otherwise.

I tried to fix it by creating an if statement that would check if both Hashmaps are of the same size, but this didn't do anything.

Here's my solution:

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()){
            return false;
        }
        HashMap<Character, Integer> stringS = new HashMap<>();
        HashMap<Character, Integer> stringT = new HashMap<>();
        for(int i = 0; i < s.length(); i++){
            stringS.put(s.charAt(i), stringS.getOrDefault(s.charAt(i), 0) + 1);
        }
        for(int i = 0; i < t.length(); i++){
            stringT.put(t.charAt(i), stringT.getOrDefault(t.charAt(i), 0) + 1);
        }
        for(int i = 0; i < stringS.size(); i++){
            if(!stringT.containsKey(s.charAt(i)) || !stringT.get(s.charAt(i)).equals(stringS.get(s.charAt(i)))){
                return false;
            }
        }
        return true;
    }
}

It passes 41/42 test cases, but fails the following one: Input s = "ills" t = "dill" Output: true Expected: false

Upvotes: -2

Views: 160

Answers (1)

Syed Sheheryar Umair
Syed Sheheryar Umair

Reputation: 109

There are a few issues I think in your code. The correct code will look like this. I have simulated this test code with your scenario and it is passing it.

 class Solution {
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) {
        return false;
    }

    HashMap<Character, Integer> stringS = new HashMap<>();
    HashMap<Character, Integer> stringT = new HashMap<>();


    for (int i = 0; i < s.length(); i++) {
        stringS.put(s.charAt(i), stringS.getOrDefault(s.charAt(i), 0) + 1);
    }

    for (int i = 0; i < t.length(); i++) {
        stringT.put(t.charAt(i), stringT.getOrDefault(t.charAt(i), 0) + 1);
    }

    // Check if the frequencies of characters match
    for (char c : stringS.keySet()) {
        if (!stringT.containsKey(c) || !stringT.get(c).equals(stringS.get(c))) {
            return false;
        }
    }

    return true;
}
}

The issue is

  • The loop is iterating up to the size of 'stringS' but it should iterate over the characters of the strings
  • The condition for checking whether the frequencies match is incorrect

Upvotes: 3

Related Questions