Anagrams are strings that are made up of the same set of letters. There are many ways to use anagrams in technical interview questions. The one that I got in my most recent round of technical interviews was along the lines of “remove all words in a list that are anagrams of words that have come before”.
The key function to working with anagrams in any algorithmic challenge is the anagram check code, and we’ll cover how to write Python anagram check code in this post.
In this post, we’ll cover:
- Anagram check Python code
- Removing all anagrams from a list with Python
- Group anagrams with Python
- Summary of Anagram Python Technical Interview Questions and Solutions
Check if two strings are anagrams
This is the core functionality of working with anagrams in Python. We need to be able to check if two strings are anagrams of each other. Remember that anagrams are words that have the same letters in different positions. For example, “slick” and “licks”.
So how do we check if two strings are anagrams? We need to make sure that they both contain the same letters and the same number of each letter. The easiest way to do this anagram check Python code is to use the `sorted` function.
We will create an `are_anagrams` function which takes two parameters, `a` and `b`, the two strings we want to check if they are anagrams or not. All we are going to do is turn the strings into sorted lists of their lower case letters. We’ll do this by calling the `sorted` function around the string with the `lower()` function called on it already. Note that `sorted` returns a list!
def are_anagrams(a: str, b: str):
a = sorted(a.lower())
b = sorted(b.lower())
return a == b
print(are_anagrams("abc", "cba"))
print(are_anagrams("GHHZ", "ZHgh"))
print(are_anagrams("not slick", "slick"))
print(are_anagrams("Yujian is Awesome", "Awesome Yujian is"))
Note: Why do we use `==` and not `is`? Because `==` evaluates the value of the compared objects while `is` checks if the aliases point to the same object. The above function should show the below results once it is run.
Remove all anagrams from a list of strings with Python
Now that we’ve created a basic Python anagram check function, let’s see how we can use it in a broader context. Let’s explore one of the technical interview problems I recently encountered.
You’re given a list of strings. Your goal is to find a way to return the number of distinct arrangements of letters in the list. In other words, your goal is to find the number of strings left once you remove all duplicate anagrams.
Let’s start by creating a function called `remove_duplicates`. Our function will take one parameter, the list of strings. Let’s create two lists in our function. One will hold the unique string configurations we see and the second will hold the “cleaned” version of the list of strings without repeated anagrams.
Next, we’ll loop through each entry in the entries list. If the sorted version of the lower case of the string is already in the list of uniques, then we should just skip this string. Otherwise, we’ll append the sorted, lowercase version of the string to uniques and append the string to the cleaned list.
I have printed out the cleaned list just so we can see it. It should be the first instance of each distinct string configuration we have. In the example below, the length should be 3.
def remove_duplicates(entries: list[str]):
uniques = []
cleaned = []
for entry in entries:
if sorted(entry.lower()) in uniques:
continue
uniques.append(sorted(entry.lower()))
cleaned.append(entry)
print(cleaned)
return len(cleaned)
entries = ["abc", "bca", "GhZH", "gzHH", "Yujian is Awesome", "Awesome Yujian Is"]
print(remove_duplicates(entries))
If we run this script, we should see an output like the one below.
Python anagram grouping problem
Another technical interview question that I’ve seen is grouping anagrams together. Just like the question above, you are provided with a list of strings. This time the problem statement is to find all the words that are anagrams of each other and group them together. In our example, we will return a dictionary of the words that are anagrams grouped together.
Our `group_anagrams` function will take one parameter, a list of strings. The first thing we’ll do is initialize an empty dictionary of all the grouped strings. Then, we’ll loop through each entry in the list and check if the sorted letters of an entry are in the dictionary. If the string is not, then we add an entry for it and initialize a list containing the current string. Otherwise, we append the current string to an existing entry. Finally, we return the dictionary.
def group_anagrams(entries: list[str]):
grouped = {}
for entry in entries:
_sorted = "".join(sorted(entry.lower()))
if _sorted not in grouped:
grouped[_sorted] = [entry]
elif _sorted in grouped.keys():
grouped[_sorted].append(entry)
return grouped
entries = ["abc", "bca", "GhZH", "gzHH", "Yujian is Awesome", "Awesome Yujian Is"]
print(group_anagrams(entries))
Running the program above will get you something like the image below. The anagrams will be grouped together and sorted by key based on the letters in the word. Notice that the spaces of the strings are removed! This is because we `joined` the letters without any spaces to create these keys.
Summary of Working with Python Anagrams
Classifying strings as anagrams through Python is an interesting topic. It’s quite easy to do with Python’s built-in function that sorts strings into lists of alphabetically ordered letters. All we have to do is cast the string into lowercase and call the `sorted` function on it.
Other than just comparing strings to see if they are anagrams, we also covered two technical interview questions around anagrams. We covered how to remove all the anagrams from a list so that it only contains distinct configurations of letters and how to group anagrams together with Python.
Further Reading
- Python Counting Sort Guide with Implementation
- Solution to 295. LeetCode Find Median of Data Stream with Python
- Private Variables in Python
- RuntimeError: Event Loop is Closed for
asyncio
- How to Build an AI Content Moderation System
I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.
