LC#242: Valid Anagram : LeetCode solution : Python
Description: Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
Example 1:
Input : s = "anagram", t = "nagaram"
Output: true
Example 2:
Input : s = "rat", t = "car"
Output: false
Constraints:
-
1 <= s.length, t.length <= 5 * 104
-
s and t consist of lowercase English letters.
Solution
Brute Force:
- Find count of each character. If the count is same then they match.
- Time: O(S+T) → time to loop over the string to build the map.
- Space: O(S+T) → space of the two hash maps
Show code
Revised Solution:
We can revise this solution to improve the space complexity to O(1) Assumption: Sorting algo’s dont need additional extra memory
- Once sorted both strings should be equal.
- Time: O(S+T)
- Space: O(1)
return sorted(s) == sorted(t)
Conculsion:
Now that you have a good understanding of the Valid Anagram problem & the solution. You can View problem on Leetcode or View solution on Neetcode