242_Valid Anagram
Level: easy
Tag: string, sort, hash table
Question
Given two strings s and t, write a function to determine if t is an anagram of s.
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?Idea
If s and t have different lengths, t must not be an anagram of s and we can return early.
For the main body of the algorithm, there are several solutions with different time complexity.
Sort both strings and compare them. If t is an anagram of s, sorting both strings will result in two identical strings.
Count occurrences of each letter in the two strings, store in dictionary, and compare two dictionaries. If t is an anagram of s, the two dictionaries should be equal.
Complexity 1
Time complexity :. Assume that
nis the length ofsandt, sorting costs and comparing two strings costs . Sorting time dominates and the overall time complexity is .Space complexity : . Space depends on the sorting implementation which, usually, costs O(1) auxiliary space if
heapsortis used.
Complexity 2
Time complexity :. Because we access each letter only once.
Space complexity : . Because at most we have 26 various letters to store in the dictionary. It's a constant as the length of
sandtincrease.
Solution 1 (sort)
Solution 2 (no sort, using dictionary)
Solution 3 (no sort, using count table, same time/space complexity as solution 2)
Questions
What if the inputs contain unicode characters?
Last updated
Was this helpful?