⬡ Introduction
Have you ever noticed that the word "listen" and the word "silent" use the exact same letters? That is what an anagram is — two words or strings that contain the same characters but arranged in a different order.
For example, "triangle" and "integral" are anagrams. So are "eat" and "tea". The letters are identical, just shuffled around.
Now, anagram check of two strings is a classic problem in programming. The goal is to write a program that takes two strings as input and tells you whether they are anagrams of each other. This is a very common question in coding interviews and university assignments, especially when learning about string comparison and algorithms.
⬢ Problem Statement
Given two strings, write a program to check anagram — that is, determine whether the two strings are anagrams of each other or not.
Example
Input: "listen" and "silent"
Output: Anagram ✅
Input: "hello" and "world"
Output: Not Anagram ❌
⣏ Input Format
- 01 The program takes two strings as input from the user.
- 02 Each string can contain letters (both uppercase and lowercase). Spaces are allowed but will be ignored during comparison.
- 03 No special handling of numbers or special characters is needed for this basic version.
String 1: Race Car
String 2: Car Race
⣷ Output Format
The program prints one of the following messages based on the result of the string comparison:
⎍ Flowchart
Here is a step-by-step description of the flowchart for the anagram check algorithm:
- 01 Start the program.
- 02 Read two strings from the user — call them str1 and str2.
- 03 Clean both strings: convert to lowercase and remove all spaces.
- 04 Sort the characters of both strings alphabetically.
- 05 Compare the two sorted strings.
- 06 If equal: print "Anagrams". If not: print "Not Anagrams".
- 07 Stop.
⌗ Pseudocode
Here is the clean pseudocode for the anagram check of two strings algorithm. Pseudocode is a plain-English description of the logic before we write actual code.
// Step 1: Read inputs
INPUT str1, str2
// Step 2: Clean both strings
str1 ← lowercase(remove_spaces(str1))
str2 ← lowercase(remove_spaces(str2))
// Step 3: Sort characters
sorted1 ← sort(str1)
sorted2 ← sort(str2)
// Step 4: Compare
IF sorted1 == sorted2 THEN
PRINT "The strings are Anagrams"
ELSE
PRINT "The strings are NOT Anagrams"
END IF
END
/> Python Program
Below is the full working anagram program written in Python. It is beginner-friendly, uses clear variable names, and handles both uppercase/lowercase and spaces properly.
# Anagram Check of Two Strings - Python Program
# Function to check if two strings are anagrams
def check_anagram(str1, str2):
# Step 1: Clean both strings
# Remove spaces and convert to lowercase
cleaned1 = str1.replace(" ", "").lower()
cleaned2 = str2.replace(" ", "").lower()
# Step 2: Sort the characters of both strings
sorted1 = sorted(cleaned1)
sorted2 = sorted(cleaned2)
# Step 3: Compare the sorted versions
if sorted1 == sorted2:
return True
else:
return False
# Main program
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
if check_anagram(str1, str2):
print("The strings are Anagrams.")
else:
print("The strings are NOT Anagrams.")
⌕ Explanation of the Program
Let's walk through the program step by step so that it is easy to understand.
Step 1 — Define a function
We create a function called check_anagram that takes two strings as parameters. Using a function makes the code clean and reusable.
Step 2 — Clean the strings
str1.replace(" ", "").lower()
This line does two things at once. It removes all spaces using .replace(" ", "") and then converts everything to lowercase using .lower(). This makes sure that "Race Car" and "car race" are treated the same way.
Step 3 — Sort the characters
sorted(cleaned1)
Python's built-in sorted() function takes a string and returns a list of its characters in alphabetical order. For example, "listen" becomes ['e', 'i', 'l', 'n', 's', 't'].
Step 4 — Compare the sorted lists
If the sorted character lists of both strings are equal, then the strings must have the same characters in the same count. That means they are anagrams. If not, they are not anagrams.
Step 5 — Main program takes input and prints result
The last block takes two strings from the user with input(), calls the function, and prints the appropriate message.
⏱ Time & Space Complexity
Time Complexity — O(n log n)
The most expensive operation in this algorithm is sorting. Python's sorted() function uses Timsort under the hood, which runs in O(n log n) time, where n is the length of the string. We sort two strings, but that is still O(n log n) overall since constants are dropped in Big-O notation.
Space Complexity — O(n)
The sorted() function creates a new list to hold the sorted characters. This list takes O(n) extra space, where n is the number of characters in the string. The cleaned versions also take O(n) space. So overall space complexity is O(n).
⊞ Test Cases
Here are four test cases to verify the correctness of the anagram program. These cover typical scenarios you should always test.
| # | String 1 | String 2 | Expected Output | Result |
|---|---|---|---|---|
| 1 | listen |
silent |
The strings are Anagrams. | Pass |
| 2 | hello |
world |
The strings are NOT Anagrams. | Fail |
| 3 | Race Car |
Car Race |
The strings are Anagrams. | Pass |
| 4 | Triangle |
Integral |
The strings are Anagrams. | Pass |
| 5 | abc |
ab |
The strings are NOT Anagrams. | Fail |
Test case 3 shows that the program correctly handles spaces and uppercase letters by cleaning both strings before comparison. Test case 5 shows that strings of different lengths are always rejected quickly.
? Frequently Asked Questions
Counter from the collections module) to count character frequencies. If both strings produce the same frequency map, they are anagrams. This runs in O(n) time and O(1) space (since there are at most 26 lowercase letters).◉ Conclusion
In this tutorial, we covered the anagram check of two strings from scratch. We started with a simple explanation of what an anagram is, walked through the problem statement, and then built a clean Python program step by step.
The core idea is simple: clean both strings (remove spaces, lowercase), sort their characters, and compare. If the sorted versions match, the strings are anagrams.
The algorithm runs in O(n log n) time due to sorting and uses O(n) extra space. For interviews or performance-critical code, you can upgrade to the frequency counter approach for O(n) time.
Keep coding and keep exploring. One problem at a time — that is how every great programmer got started!