DSA problem
Check if Two Strings are Anagrams
Given two strings s1 and s2, check whether they are anagrams of each other. Two strings are anagrams if they contain the same characters with the same frequencies, just in a different order.
A sorting approach sorts both strings and compares them in O(n log n). The optimal approach uses a frequency count: increment counts for the first string and decrement for the second, using a single array of size 26 for lowercase English letters. If every value ends at 0, the strings are anagrams. This O(n) technique is a direct application of counting, and anagram checking shows up in word games, cryptography, and as a sub-problem in group-anagrams - a frequently asked interview question.
Examples
s1 = "listen", s2 = "silent"trues1 = "hello", s2 = "world"falseConstraints
- 1 <= s1.length, s2.length <= 10^5
- Strings contain only lowercase English letters
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.