Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Problem in solving valid anagram problem in leetcode

leetcode Problem 242

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Read the following code as my approach to solve:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        
        if len(s) != len(t):
            return "false"
        
        dict1 = {}
        
        for key in s:
            if key in dict1:
                dict1[key] +=1
            else:
                dict1[key] =1

        dict2 = {}
        
        for key in t:
            if key in dict2:
                dict2[key] +=1
            else:
                dict2[key] =1

        for key in dict1:
            if dict1[key] != dict2.get(key, 0):
                return "false"

        for key in dict2:
            if dict2[key] != dict1.get(key, 0):
                return "false"

        return "true"

when I’m running the above code using input s = "a" and t = "ab" in my vscode editor, it gives false, which is correct. But the same code is not passing in the leetcode returning true, which is not the correct result. could you please guide, how to tweak and correct the same code??

>Solution :

you should return a boolean, not a string: i.e. say return False instead of return "false"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading