#5 Valid anagram

https://leetcode.com/problems/valid-anagram/

For two strings to be anagrams, their lengths must be equal and every character must appear in each string for the same ‘count’.

We can convert the strings to character arrays and then sort them. If the two sorted arrays are equal (remember array’s are value types in Swift) – the strings must be anagrams. This would be a O(n logn) time and O(n) space solution (sorting using the standard library in swift takes O(n) space)

The other solution uses a Map to record the count of each character in the source string and then iterates over the target string to check if every character can be mapped to a character in source string -> as we iterate over target, we also need to update the map to reduce the count of ‘seen’ characters. We also need to be sure to have lengths equal check before we get into the loop – otherwise we could have a scenario where the source string has a character that is not needed by the target string -> in this case we need to return false.

One thought on “#5 Valid anagram

  1. Pingback: #6 Group Anagrams | Indrajit Shanbhag

Leave a comment