Hashing · Easy
Anagram Check
Solve it on DeVert Campus - free code runner
Problem
Given two strings s and t consisting of lowercase English letters, determine whether t is an anagram of s, meaning t can be formed by rearranging all of the letters of s exactly once each. Print YES if they are anagrams of each other, and NO otherwise.
Input and output
Input: The first line contains string s. The second line contains string t.
Output: Print YES if t is an anagram of s, otherwise print NO.
Example
Input: listen silent Output: YES
Constraints
1 <= |s|, |t| <= 10^5. Both strings consist only of lowercase English letters.
Key observation
Checking the LENGTHS first is a cheap, instant way to reject the vast majority of non-anagram pairs before doing any counting work at all - a small but sensible early-exit optimization.
Intuition
Check whether one string can be rearranged to exactly form another, using every letter exactly once.
Brute force: Sort both strings' characters and compare the sorted results directly - this works too (and is simple), but costs O(n log n) for the sort, when a frequency-count comparison achieves the same check in linear time.
Optimised: Since there are only 26 possible lowercase letters, a simple frequency array (or hash map) built in one pass over each string, then compared directly, checks for a valid anagram in O(n) total - faster than sorting, which needlessly imposes an ordering that isn't actually needed for this comparison.
Step by step
1. If the two strings have different LENGTHS, they can never be anagrams - answer No immediately.
2. Count the frequency of each of the 26 lowercase letters in BOTH strings.
3. Compare the two frequency counts - if every letter's count matches exactly, they're anagrams.
Complexity
Time: O(n) - one pass to count each string's letters, plus a fixed 26-element comparison.
Space: O(1) - the frequency arrays are always exactly 26 slots, regardless of string length.
Edge cases
Strings of different lengths are immediately NO. Two identical strings are trivially anagrams (YES).
Interview tip
Be ready to mention the sorting-based alternative too, and to explain precisely why the counting approach is asymptotically better (O(n) versus O(n log n)) even though both are perfectly valid, simple solutions.