Valid Anagram in Python

Thu Jul 18 2024
Valid Anagram

Checking if two strings are anagrams is a common task in programming. An anagram is when two strings have the same characters but in a different order. This task helps you understand string manipulation and comparison in Python. In this blog, we'll explore how to check if two strings are valid anagrams with a real-life example, a clear problem statement, and step-by-step instructions. We'll provide the full code, explain how it works, discuss its efficiency, and answer some common questions.

Real-life example

Imagine you’re working on a spell-checker or a word game application. You need to determine if two words are anagrams, like "listen" and "silent". This can be useful for games like Scrabble or for creating anagrams as part of a word puzzle.

Problem statement

Given two strings, we need to write a Python function that checks if they are anagrams of each other.

Sample input

python
1s1 = "listen"
2s2 = "silent"

Sample output

python
1output = True

Idea to solve

The idea is to sort both strings and compare them. If the sorted versions of the strings are the same, then the strings are anagrams. Alternatively, we can count the frequency of each character in both strings and compare these counts.

Pseudo code

Here’s the pseudo code for checking if two strings are anagrams:

  • Define a function is_anagram that takes two strings s1 and s2.
  • If the lengths of the strings are not the same, return False.
  • Sort both strings and compare them.
  • If they are the same, return True.
  • Otherwise, return False.

Full code

Here’s the complete Python code to check if two strings are valid anagrams:

python
1def is_anagram(s1, s2):
2    # If lengths are not equal, they cannot be anagrams
3    if len(s1) != len(s2):
4        return False
5    
6    # Sort both strings and compare
7    return sorted(s1) == sorted(s2)
8
9# Sample input
10s1 = "listen"
11s2 = "silent"
12# Calling the function and printing the result
13output = is_anagram(s1, s2)
14print("Are the strings anagrams?", output)

Explanation of the code

  • Function Definition: We define a function is_anagram that takes two strings s1 and s2.
  • Length Check: If the lengths of the strings are not equal, we return False immediately because they cannot be anagrams.
  • Sorting and Comparison: We sort both strings and compare them. If they are the same, the function returns True. Otherwise, it returns False.
  • Function Call: We call the is_anagram function with the sample inputs "listen" and "silent" and print the result.

Time complexity

The time complexity of this approach is O(nlogn) due to the sorting step, where n is the length of the strings. Sorting is the most time-consuming part of this algorithm.

FAQs

What is a valid anagram?

What is an example of an anagram?

What does anagram mean?

Which is an anagram?

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.