Given two strings
Output: true
Explanation: "nagaram" is an anagram of "anagram" word, we can form the word "nagaram" by re-arranging leters from "anagram" only once.
Output: true
Explanation: "car" cannot be formed by re-arranging leters from "rat".
Constraints:
1 <= s.length, t.length <= 5 * 104 s andt consist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
Contents
Solution 1 - Using an array to store count of each character appearance Solution 2 - Using two HashMaps to store count of each character appearance Solution 3 - Using one HashMap to store count of each character appearance (Solution to follow-up question)
In this approach, we will use a temporary array to store each character count from input string
-
We will create a function
usingArray that takes input arguments strings andt . -
Base case is, if input strings
s andt lengths are not same, then we can simply returnfalse because these strings won't be anagrams of each other. -
Create a temporary array with size as
26 if the characters going to be lowercase or uppercase english alphabet letters. (If the characters are going to be ASCII characters, then you can initialize array with128 size) -
Then, for each character in input string
t add character count in correponding position. -
Then, for each character in input string
s , decrement the count from temporary array that we have created above.-
If the count at character position becomes
-1 , this means that the string is not an anagram. -
If the count at character position never becomes
-1 , then both strings are anagrams of each other.
-
If the count at character position becomes
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1) since we are creating a temporary array with size 26 or 128 depends on characters type.
In this approach, we will use a
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n) since we are storing character count into a
This approach is same as solution 1, instead of using an array we will be using a HashMap, so that the solution will work for any type of characters that are in input strings like ASCII or Unicode etc.
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(n) since we are storing character count into a
Above implementations source code can be found at