Tutorialspoint
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
StringsKPMGSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Check if both strings have the same length - if not, return false immediately.
 Step 2: Create an empty object to store character frequencies from the first string.
 Step 3: Iterate through the first string and count the frequency of each character.
 Step 4: Iterate through the second string and decrement the count for each character.
 Step 5: If any character is not found or count becomes negative, return false.
 Step 6: If all characters are matched with correct frequencies, return true.

Submitted Code :