Is a string an anagram?
An anagram is a word or phrase formed by rearranging the letters of another word or phrase. For example, “elbow” and “below” are anagrams of each other. In coding interviews and programming challenges, you may be asked to write a function that checks if two input strings are anagrams. Here’s how to do this in both Python and JavaScript.
Python Solution
Here is one way to check if two strings are anagrams in Python:
def are_anagrams(str1, str2):
# Convert both strings to lowercase and remove whitespace
str1 = str1.replace(" ", "").lower()
str2 = str2.replace(" ", "").lower()
# Check if lengths are different
if len(str1) != len(str2):
return False
# Sort the strings and compare
return sorted(str1) == sorted(str2)
This works by first cleaning up the input strings - converting them to lowercase and removing any whitespace.
We then check if the lengths are different - if so, they cannot be anagrams.
Finally, we sort each string alphabetically and compare the sorted versions. If they are equal, the original strings must have been anagrams.
JavaScript Solution
Similarly in JavaScript:
function areAnagrams(str1, str2) {
// Remove whitespace and lowercase
let s1 = str1.replace(/\s/g, '').toLowerCase();
let s2 = str2.replace(/\s/g, '').toLowerCase();
// Check length
if (s1.length !== s2.length) return false;
// Sort and compare
let sorted1 = s1.split('').sort().join('');
let sorted2 = s2.split('').sort().join('');
return sorted1 === sorted2;
}
The process is essentially the same - clean up the strings, check lengths, sort and compare.
This demonstrates how the core algorithm remains the same across languages, with minor syntactical differences.
Checking if two strings are anagrams is a common interview challenge, and solving it shows you can work with strings and sorting algorithms. With practice, translating a solution between Python and JavaScript gets easier.
Let me know if you would like me to expand or modify this draft blog post in any way!