Implement the validAnagramCheck method that checks whether two strings are anagrams.

The input contains two strings, first and second. Your task is to check whether both strings are anagrams of each other.

Two strings are anagrams when they contain exactly the same characters with the same frequency, but the order may be different. For example, listen and silent are anagrams.

Example 1

Input
first (string) = listen
second (string) = silent
Returns (boolean) true

Example 2

Input
first (string) = anagram
second (string) = nagaram
Returns (boolean) true

Example 3

Input
first (string) = rat
second (string) = car
Returns (boolean) false

First compare the lengths. If the lengths are different, the strings cannot be anagrams.

Then count how many times each character appears in the first string. While scanning the second string, reduce the matching character count.

If any count becomes negative or a character is missing, the strings are not anagrams. If all counts balance to zero, they are valid anagrams.

Pseudocode:

function validAnagramCheck(first, second):
    if length(first) != length(second):
        return false
    counts = empty map
    for each character in first:
        counts[character]++
    for each character in second:
        if character does not exist in counts or counts[character] == 0:
            return false
        counts[character]--
    return true
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.