Algorithm


  1. Input:

    • Take two input strings, str1 and str2.
  2. Preprocessing:

    • Remove spaces from both strings.
    • Convert both strings to lowercase for case-insensitive comparison.
  3. Length Check:

    • If the lengths of str1 and str2 are not equal, return False (they cannot be anagrams).
  4. Character Frequency Count:

    • Create two dictionaries, char_count_str1 and char_count_str2, to store the frequency of each character in str1 and str2.
  5. Count Characters in str1:

    • Iterate through each character in str1.
    • Update the corresponding entry in char_count_str1 by incrementing its count.
  6. Count Characters in str2:

    • Iterate through each character in str2.
    • Update the corresponding entry in char_count_str2 by incrementing its count.
  7. Comparison:

    • Check if char_count_str1 is equal to char_count_str2.
    • If they are equal, return True (strings are anagrams).
    • If they are not equal, return False (strings are not anagrams).
  8. Output:

    • Print the result or use it as needed

 

Code Examples

#1 Code Example- Python program to check if two strings are anagrams using sorted()

Code - Python Programming

str1 = "Race"
str2 = "Care"

# convert both the strings into lowercase
str1 = str1.lower()
str2 = str2.lower()

# check if length is same
if(len(str1) == len(str2)):

    # sort the strings
    sorted_str1 = sorted(str1)
    sorted_str2 = sorted(str2)

    # if sorted char arrays are same
    if(sorted_str1 == sorted_str2):
        print(str1 + " and " + str2 + " are anagram.")
    else:
        print(str1 + " and " + str2 + " are not anagram.")

else:
    print(str1 + " and " + str2 + " are not anagram.")
Copy The Code & Try With Live Editor

Output

x
+
cmd
race and care are anagram.
Advertisements

Demonstration


Python Programing Example to Check If Two Strings are Anagram-DevsEnv