DEV Community

Cover image for LeetCode Challenge: 242. Valid Anagram - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

LeetCode Challenge: 242. Valid Anagram - JavaScript Solution πŸš€

Top Interview 150

The Valid Anagram problem is a straightforward challenge involving string manipulation and character counting. Let’s solve LeetCode 242: Valid Anagram step by step.


πŸš€ Problem Description

Given two strings s and t:

  • Return true if t is an anagram of s.
  • Otherwise, return false.

An anagram is a word or phrase formed by rearranging the letters of another. Both strings must have the same characters in the same frequencies.


πŸ’‘ Examples

Example 1

Input: s = "anagram", t = "nagaram"  
Output: true  
Explanation: Both strings have the same characters with the same frequencies.
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: s = "rat", t = "car"  
Output: false  
Explanation: The characters in `t` are not the same as in `s`.
Enter fullscreen mode Exit fullscreen mode

πŸ† JavaScript Solution

We can efficiently solve this problem by counting the frequency of characters in both strings and comparing the counts.


Implementation

var isAnagram = function(s, t) {
    if (s.length !== t.length) return false;

    const charCount = {};

    for (let char of s) {
        charCount[char] = (charCount[char] || 0) + 1;
    }

    for (let char of t) {
        if (!charCount[char]) return false;
        charCount[char]--;
    }

    return true;
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Count Characters in s:

    • Use a hash map (charCount) to track the frequency of each character in s.
  2. Subtract Characters in t:

    • For each character in t, decrement its count in charCount.
    • If a character in t is missing or its count becomes negative, return false.
  3. Return True:

    • If all characters match and their counts balance, return true.

πŸ”‘ Complexity Analysis

  • Time Complexity: O(n), where n is the length of s (or t).

    • Each character is processed once.
  • Space Complexity: O(1), as the hash map stores at most 26 entries for lowercase English letters.


πŸ“‹ Dry Run

Input: s = "anagram", t = "nagaram"
Dry Run

Output: true


Follow-Up: Unicode Characters
For inputs containing Unicode characters, the solution can be adapted as follows:

  • Instead of assuming lowercase English letters, allow any character as a key in the hash map.
  • This approach is already supported by the above implementation, as JavaScript hash maps ({} or Map) can store any string as a key.

✨ Pro Tips for Interviews

  1. Discuss Sorting Approach:
    • An alternative solution involves sorting both strings and comparing them.
    • Time Complexity: O(nlogn) due to sorting.
var isAnagram = function(s, t) {
    return s.split("").sort().join("") === t.split("").sort().join("");
};
Enter fullscreen mode Exit fullscreen mode


`

  1. Clarify Edge Cases:
    • Different lengths: s = "abc", t = "abcd".
    • Empty strings: s = "", t = "".

πŸ“š Learn More

Check out the full explanation and code walkthrough on my previous Dev.to post:
πŸ‘‰ Word Pattern - JavaScript Solution

What’s your preferred method to solve this problem? Let’s discuss! πŸš€


Study

Top comments (1)

Collapse
 
rahulgithubweb profile image
Rahul Kumar Barnwal

Follow Me on GitHub πŸš€

If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.

Don't forget to follow for more updates!