Write a program that checks if two strings are anagrams.
- User
Write a program that checks if two strings are anagrams.
Assistant
Write a program that checks if two strings are anagrams.
The user wants a program to check if two strings are anagrams. I should provide a solution in a popular programming language like Python or Java. Python is generally more concise and readable for this type of task.
Understanding Anagrams: Two strings are anagrams if they contain the exact same characters with the exact same frequencies, ignoring order. Example: "listen" and "silent". Considerations:
Approaches:
Sorting:
Frequency Counter (Hash Map / Dictionary):
Implementation Plan (Python): I will provide a Python solution because it's the most accessible. I will implement the sorting method for simplicity and the counter method for efficiency.
sorted() and join().collections.Counter or a manual dictionary.Refining the Code:
I should define a function is_anagram(str1, str2).
s1.replace(" ", "").lower()Drafting the Python Code:
def is_anagram(str1, str2):
# Remove spaces and convert to lowercase for a standard check
# If you want a strict check (case-sensitive, space-sensitive), remove these lines
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check length first for optimization
if len(str1) != len(str2):
return False
# Method 1: Sorting
return sorted(str1) == sorted(str2)
Drafting the Java Code (Alternative): Some users prefer Java. I'll provide Python as the primary and maybe Java as a secondary option or just stick to Python if not asked. Python is the safest bet for a general "write a program" request.
Let's stick to Python but offer two logic approaches (Sorting vs. Hash Map).
Plan:
Code Structure:
def check_anagram(s1, s2):
# Logic
pass
# Driver code
s1 = "listen"
s2 = "silent"
print(check_anagram(s1, s2))
I will provide the "Sorting" approach as the primary answer because it is one line of logic and easy to read. I will mention the approach as an optimization.
Self-Correction: Should I handle non-alphabetic characters? sorted() works on anything. replace(" ", "") only handles spaces. Punctuation like "Clint Eastwood" vs "Old West Action" requires stripping punctuation.
Let's stick to the simple version: Case insensitive, space insensitive is the most common interview answer.
I'll implement a function that cleans the string (lowercase + replace spaces).
Final Code Construction:
def is_anagram(str1, str2):
# 1. Clean the strings (optional, but good practice for anagrams)
# Remove spaces and make lowercase
clean_str1 = str1.replace(" ", "").lower()
clean_str2 = str2.replace(" ", "").lower()
# 2. Check if lengths match
if len(clean_str1) != len(clean_str2):
return False
# 3. Sort and Compare
# If the sorted lists of characters are equal, they are anagrams
return sorted(clean_str1) == sorted(clean_str2)
I will also include a small "Driver" block to make it runnable.
What if the user wants Java? I'll provide the solution in Python (most popular for scripts) and C++ or Java as well, or just Python. I'll stick to Python but make the explanation clear so it can be translated. I'll provide Python code.
Detailed explanation steps:
Let's also mention the approach using a dictionary/hash map for completeness.
Optimized Approach (Frequency Counter): If the string is 1 million chars long, sorting () is slower than counting (). Code:
def is_anagram_optimized(str1, str2):
# ... cleaning ...
count = {}
for char in str1:
count[char] = count.get(char, 0) + 1
for char in str2:
if char not in count: return False
count[char] -= 1
if count[char] < 0: return False
return True
Or use collections.Counter.
I will present the Sorting method as the primary solution because it is the most readable "one-liner" logic, and then provide the Frequency method as the "efficient" solution.
Let's write the response. Here are two ways to solve this in Python.
This approach sorts the characters in both strings alphabetically and compares them. If the sorted lists are identical, the strings are anagrams.
Time Complexity:
def is_anagram(str1, str2):
# 1. Clean the strings: remove spaces and convert to lowercase
# This ensures "Listen" and "Silent" match, or "Dormitory" and "Dirty room"
s1 = str1.replace(" ", "").lower()
s2 = str2.replace(" ", "").lower()
# 2. Check if lengths match (optimization)
if len(s1) != len(s2):
return False
# 3. Sort and Compare
return sorted(s1) == sorted(s2)
# --- Test the program ---
string_a = "Listen"
string_b = "Silent"
if is_anagram(string_a, string_b):
print(f'"{string_a}" and "{string_b}" are anagrams.')
else:
print(f'"{string_a}" and "{string_b}" are NOT anagrams.')
This approach counts the frequency of every character. It is faster () because it doesn't need to sort the data, making it better for very long strings.
Time Complexity:
def is_anagram_fast(str1, str2):
# 1. Clean the strings
s1 = str1.replace(" ", "").lower()
s2 = str2.replace(" ", "").lower()
# 2. Check lengths
if len(s1) != len(s2):
return False
# 3. Count character frequencies
count = {}
# Increment count for characters in first string
for char in s1:
count[char] = count.get(char, 0) + 1
# Decrement count for characters in second string
for char in s2:
if char not in count:
return False
count[char] -= 1
if count[char] < 0:
return False
return True
# --- Test the program ---
print(is_anagram_fast("Debit Card", "Bad Credit")) # True
print(is_anagram_fast("Hello", "World")) # False
.lower() and .replace(" ", "") so that differences in capitalization (A vs a) or spacing don't cause a false negative.collections.Counter(s1) == collections.Counter(s2) to achieve this in one line.