Implement the areTextsAnagram method that checks whether two texts contain the same characters with the same frequencies.

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 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) = apple
second (string) = papel
Returns (boolean) true

Example 3

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

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

Otherwise, count characters from the first string and reduce the counts using the second string. If any count becomes invalid or any count remains after processing, return false; otherwise return true.

Pseudocode:

function areTextsAnagram(first, second):
    if length(first) != length(second):
        return false
    frequency = empty map
    for each character in first:
        frequency[character]++
    for each character in second:
        if character not in frequency:
            return false
        frequency[character]--
        if frequency[character] < 0:
            return false
    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.