Algorithm
-
Input:
- Take two input strings,
str1
andstr2
.
- Take two input strings,
-
Preprocessing:
- Remove spaces from both strings.
- Convert both strings to lowercase for case-insensitive comparison.
-
Length Check:
- If the lengths of
str1
andstr2
are not equal, returnFalse
(they cannot be anagrams).
- If the lengths of
-
Character Frequency Count:
- Create two dictionaries,
char_count_str1
andchar_count_str2
, to store the frequency of each character instr1
andstr2
.
- Create two dictionaries,
-
Count Characters in
str1
:- Iterate through each character in
str1
. - Update the corresponding entry in
char_count_str1
by incrementing its count.
- Iterate through each character in
-
Count Characters in
str2
:- Iterate through each character in
str2
. - Update the corresponding entry in
char_count_str2
by incrementing its count.
- Iterate through each character in
-
Comparison:
- Check if
char_count_str1
is equal tochar_count_str2
. - If they are equal, return
True
(strings are anagrams). - If they are not equal, return
False
(strings are not anagrams).
- Check if
-
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
race and care are anagram.
Demonstration
Python Programing Example to Check If Two Strings are Anagram-DevsEnv