Post

Created by @oliverrichards
 at October 27th 2023, 9:40:39 am.

Valid Anagram

You are given two strings s and t, determine if t is an anagram of s.

An anagram is a word formed by rearranging the letters of another word.

Write a function isAnagram(s: str, t: str) -> bool to determine if t is an anagram of s.

Example 1:

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

Output: True

Example 2:

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

Output: False

Approach

One simple approach to solve this problem is to compare the sorted versions of the two input strings.

  1. If s and t are anagrams, then their sorted versions should be equal.
  2. If s and t are not anagrams, then their sorted versions will be different.

Algorithm

  1. First, check if the lengths of s and t are equal. If they are not equal, return False as they cannot be anagrams.
  2. Sort s and t using the in-built sorting function.
  3. Compare the sorted versions of s and t. If they are equal, return True, else return False.

Complexity Analysis

Since sorting the strings takes O(nlogn) time complexity, this approach has a time complexity of O(nlogn), where n is the length of the strings s and t.

Code Implementation

Here is the Python implementation of the algorithm:

def isAnagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False

    sorted_s = sorted(s)
    sorted_t = sorted(t)

    return sorted_s == sorted_t

Let's test the function with the provided examples:

# Example 1
s = "anagram"
t = "nagaram"
print(isAnagram(s, t))
# Output: True

# Example 2
s = "rat"
t = "car"
print(isAnagram(s, t))
# Output: False

The function returns the expected output for both examples, confirming that it is correctly determining if t is an anagram of s.