DSA Tutorial · Strings

Anagram Check

By TechNaga  ·  Python  ·  Beginner-Friendly  ·  5 min read

Futuristic digital data flowing

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.

Fun fact: The word "anagram" comes from the Greek word anagrammatismos, meaning "to transpose letters." Mathematicians and word game fans have been playing with anagrams for hundreds of years!

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.

Two strings are anagrams if and only if they contain exactly the same characters with exactly the same frequencies, ignoring uppercase/lowercase differences. Spaces are ignored in this solution.

Example

Input: "listen" and "silent"
Output: Anagram ✅

Input: "hello" and "world"
Output: Not Anagram ❌

Input Format

Futuristic interface analyzing data
Example Input:
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:

"The strings are Anagrams." — if both strings have the same characters in the same count.
"The strings are NOT Anagrams." — if the characters or counts do not match.

Flowchart

Here is a step-by-step description of the flowchart for the anagram check algorithm:

START Input str1, str2 (two strings from user) Lowercase + Remove Spaces Clean str1 and str2 Sort characters of both strings sorted(str1) == sorted(str2)? YES NO Print: "The strings are Anagrams" Print: "NOT Anagrams" END

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.

BEGIN
  // 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

Futuristic glowing Python logo

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.

script.py
# 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)
Due to sorting of both strings
Space Complexity
O(n)
Extra space for sorted lists

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).

Tip: If you use a frequency counter approach (counting character occurrences with a dictionary), you can achieve O(n) time complexity instead. But sorting is simpler to understand for beginners.

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

What is the difference between anagram and palindrome?
An anagram is two different strings with the same characters (e.g., "eat" and "tea"). A palindrome is a single string that reads the same forwards and backwards (e.g., "racecar"). They are completely different concepts.
Can we do anagram check of two strings in O(n) time?
Yes! Instead of sorting, you can use a dictionary (or Python's 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).
Do numbers count in an anagram check?
For basic string problems, numbers are treated just like any other character. "a1b" and "1ba" would be anagrams. The problem definition usually tells you if numbers should be handled differently.
Is this a common interview question?
Absolutely. Anagram check is one of the top 10 most common string problems in technical interviews. Interviewers use it to test your understanding of string comparison, hashing, and sorting algorithms.

Conclusion

Summary

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.

This problem is a great starting point for anyone learning about string manipulation, sorting algorithms, and comparing data in Python. Practice it, modify it, and build on it — that is how real understanding grows.

Keep coding and keep exploring. One problem at a time — that is how every great programmer got started!