Valid Anagram Leetcode Solution Python (Beats 99.45% of Submissions)

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.

Leetcode Solution (Python)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        # Set of characters in s,t
        charset_s = set(s)
        charset_t = set(t)
        
        # If the two sets differ, they are not anagrams
        if charset_s!=charset_t:
            return False
        
        for char in charset_s:
            # Count characters in s, t
            count_s = s.count(char)
            count_t = t.count(char)
            # If the counts differ, then they are not anagrams
            if count_s!= count_t:
                return False
        return True

Elements of Programming Interviews in Python: The Insiders’ Guide

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.