DEV Community

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

Posted on

2 1 1 1 1

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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!

๐Ÿ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay