Python Interview coding 5 With Funny Example
🔄 String Anagram Check: Are Two Strings Anagrams? (Python Solution)
An anagram is when two words contain the same letters in a different order. For example, "listen" and "silent" are anagrams. 🧐
In this blog, we’ll explore different ways to check for anagrams in Python and discuss real-life applications where this can be useful! 🚀
🛠️ Method 1: Sorting Approach
The simplest way to check if two strings are anagrams is by sorting their characters and comparing them.
def is_anagram_sorting(str1, str2):
return sorted(str1) == sorted(str2) # Sort and compare
# Example Usage
word1 = "listen"
word2 = "silent"
print(f"Are '{word1}' and '{word2}' anagrams? {is_anagram_sorting(word1, word2)}") # Output: True
🔍 Explanation (Line-by-Line)
sorted(str1)
→ Sorts the letters of the first string.sorted(str2)
→ Sorts the letters of the second string.return sorted(str1) == sorted(str2)
→ If they match, they are anagrams.
📊 Time and Space Complexity
- Time Complexity:
O(n log n)
→ Sorting takes logarithmic time. - Space Complexity:
O(1)
→ No extra space used.
✅ Method 2: Frequency Count (Optimized)
Instead of sorting, we can count how many times each letter appears and compare the counts.
from collections import Counter
def is_anagram_counter(str1, str2):
return Counter(str1) == Counter(str2) # Compare letter frequencies
# Example Usage
word1 = "triangle"
word2 = "integral"
print(f"Are '{word1}' and '{word2}' anagrams? {is_anagram_counter(word1, word2)}") # Output: True
🔍 Explanation (Line-by-Line)
Counter(str1)
→ Creates a dictionary with letter counts for the first string.Counter(str2)
→ Creates a dictionary with letter counts for the second string.return Counter(str1) == Counter(str2)
→ If they match, they are anagrams.
📊 Time and Space Complexity
- Time Complexity:
O(n)
→ Counting letters takes linear time. - Space Complexity:
O(1)
→ A fixed-size dictionary is used.
🏆 Conclusion: Which Method is Best?
Method | Pros | Cons | Time Complexity | Space Complexity |
---|---|---|---|---|
Sorting | Simple and easy to implement | Slower due to sorting | O(n log n) | O(1) |
Frequency Count | Fast and efficient | Uses extra space for frequency count | O(n) | O(1) |
The frequency count method is faster and more efficient, especially for large strings. 🚀
📌 Real-Life Applications of Anagram Checking
- Plagiarism Detection: Anagram checking can help detect rearranged words in plagiarized content.
- Word Games: Used in apps like Scrabble, Anagram solvers, or Crossword puzzle generators.
- Data Deduplication: Helps find similar words in a database where spelling may be altered.
- Cybersecurity: Detects scrambled or obfuscated text in encrypted messages.
Now that you know how to check for anagrams, where do you think it could be useful? Let me know in the comments! 😆
python-interview-coding-6-with-funny-example
Comments
Post a Comment