Skip to content

Latest commit

 

History

History
65 lines (48 loc) · 2.39 KB

242.Valid_Anagram(Easy).md

File metadata and controls

65 lines (48 loc) · 2.39 KB

242. Valid Anagram (Easy)

Date and Time: Jul 13, 2024, 16:50 (EST)

Link: https://leetcode.com/problems/valid-anagram/


Question:

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

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.


Example 1:

Input: s = "anagram", t = "nagaram"

Output: true

Example 2:

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

Output: false

Explanation:

Edge case:

Input: s = "a", t = "ab"

Output: false


Constraints:

  • 1 <= s.length, t.length <= 5 * 10^4

  • s and t consist of lowercase English letters.


KeyPoints:

Just build a hashmap to store s, then loop over t to decrement each element's occurence in the hashmap. And check if all elements' occurences in the hashmap are reset to 0 (which means s, t are valid anagram).


My Solution:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        sMap = {}
        for i in s:
            sMap[i] = 1 + sMap.get(i, 0)
        for i in t:
            if i in sMap:
                sMap[i] -= 1
        return max(sMap.values()) == 0

Time Complexity: $O(len(s) + len(t))$
Space Complexity: $O(len(s))$


CC BY-NC-SABY: credit must be given to the creatorNC: Only noncommercial uses of the work are permittedSA: Adaptations must be shared under the same terms