Valid Anagram
easyBlind 75NeetCode 150stringshashing
Problem
Given two strings, determine whether one is a rearrangement of the other. Two strings are anagrams when they contain exactly the same characters with the same frequencies.
Examples
Input: s = "anagram", t = "nagaram"
Output: true
Both strings use the same letters the same number of times.
Input: s = "rat", t = "car"
Output: false
The letter sets differ.
Constraints
- • 1 <= s.length, t.length <= 5 * 10^4
- • Strings consist of lowercase English letters
Hints(tap to reveal)
- 1. If the lengths differ they cannot be anagrams.
- 2. Count how many times each character appears.
Optimal approach(spoiler)
- If the two lengths differ, return false right away.
- Build a frequency count of characters in the first string.
- Decrement that count for each character in the second string.
- If any count goes negative or is non-zero at the end, return false.
- O(n) time, O(1) space for a fixed alphabet.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor