LeetCode 242

Valid Anagram

Concepts:

Hashmap

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

Brute-force Approach

Sort both strings and check if they are equal. If they are, the strings are anagrams.

Time: O(nlogn)

Space: O(1)

Optimal Approach

Initialize a hashmap (an array of length 26). Iterate through the strings, incrementing count for each character in the first string and decrementing count for each character in the second string. Check if all counts are 0.

Time: O(n)

Space: O(1)

All Problems