Algorithms and Data Structures · Junior · Question 44 of 75

How do you check that two strings are anagrams in O(n)?

Explanation

Count characters of the first string in a map, subtract the second string, and check that all counts are zero. Equal length isn't enough, and the "every character is present" check ignores how many times it appears ("aab" vs "abb"). Sorting both strings works too, but costs O(n log n).

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 44

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz