valid_anagram

Solution

	
	"""
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.
"""

def valid_anagram(left: str, right: str) -> bool:
    l_map, r_map = {}, {}
    if len(left) != len(right):
        return False
    for i in range(len(left)):
        l_map[left[i]] = 1 + l_map.get(left[i], 0)
        r_map[right[i]] = 1 + r_map.get(right[i], 0)
    return l_map == r_map

	

Tests

	
	from publicmatt.leet.problems.valid_anagram import valid_anagram


def test_simple():
    s = "anagram"
    t = "nagaram"
    assert valid_anagram(s, t)


def test_non_anagram():
    s = "rat"
    t = "car"
    assert not valid_anagram(s, t)


def test_diff_len():
    s = "racc"
    t = "car"
    assert not valid_anagram(s, t)

	
valid_anagram