
Problem
Solution
Submissions
Valid Anagram
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a JavaScript program to determine if two given strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, "listen" and "silent" are anagrams because they contain the same characters with the same frequency.
Example 1
- Input: str1 = "listen", str2 = "silent"
- Output: true
- Explanation: "listen" contains letters: l, i, s, t, e, n and "silent" contains letters: s, i, l, e, n, t. Both strings have the same characters with the same frequency, therefore they are anagrams of each other.
Example 2
- Input: str1 = "hello", str2 = "world"
- Output: false
- Explanation: "hello" contains letters: h, e, l, l, o and "world" contains letters: w, o, r, l, d. The strings have different characters and frequencies, therefore they are not anagrams of each other.
Constraints
- 1 ≤ str1.length, str2.length ≤ 5 * 10^4
- str1 and str2 consist of lowercase English letters only
- Time Complexity: O(n)
- Space Complexity: O(1) - considering fixed alphabet size
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- First check if both strings have the same length - if not, they cannot be anagrams
- Create a frequency map to count occurrences of each character in the first string
- Iterate through the second string and decrement the count for each character
- If any character count becomes negative, the strings are not anagrams
- Alternatively, you can sort both strings and compare them for equality