Problem 242
Question statement:
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Solution
Main idea:
The two strings can only be anagrams of each other, if each distinct letter appears the same number of times in each string. This can be captured by taking the underlying set of distinct letters for one of them, and for each distinct letter comparing its count in both strings. Return true if all counts are the same, and false otherwise.
Code:
1 | def isAnagram(self, s: str, t: str) -> bool: |
Comments:
Time complexity: O(len(s))
This is not a daily challenge problem. I took way too long to optimize the challenge question for (01/06/24). So I instead wrote this solution quickly.
The above code ran in 37ms, beats 98.16% of users. It uses 17.79MB of memory, beating 17.11% of users.