How to Check If Two Strings Are Anagrams of Each Other

Check if two Strings are Anagrams Without using built-in features that require Import

Generate a HashMap of frequencies of symbols for both given strings.

Then compare the two maps. If they are equal, then the strings are anagrams.

public static boolean isAnagram(String a, String b) {
return getFrequencies(a).equals(getFrequencies(b));
}

public static Map<Integer, Long> getFrequencies(String str) {

return str.codePoints()
.boxed()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
}

main()

public static void main(String[] args) {
System.out.println(isAnagram("hello", "olhel"));
System.out.println(isAnagram("hello", "olhelq"));
}

Output:

true
false

Without using any packages or imports

There are different possibilities, the optimal choice would depend on the constraints on the strings received as an input.

If we expect that input will contain only letters of the English alphabet, then we could handle this case by populating two arrays of length 26 where each element corresponds to a frequency of a particular letter (as shown in the link provided by @Federico klez Culloca in the comments). To get the result, we can compare these arrays iterating over the indices and checking values at the same index are equal. This algorithm will run in a linear time O(n) (as well as map-based solution shown above).

In case if we can't expect that symbols in the given strings would be in a particular range, then we can extract arrays of characters from both strings, sort them and compare both array character by character. This algorithm will run in a linear-logarithmic time O(n * log n) because it requires sorting. And since we are not allowed to use imports (like Arrays utility class) then we need to implement a linear-logarithmic sorting algorithm (like quicksort or merge-sort) manually.

How to check if two words are anagrams

Fastest algorithm would be to map each of the 26 English characters to a unique prime number. Then calculate the product of the string. By the fundamental theorem of arithmetic, 2 strings are anagrams if and only if their products are the same.

Checking if two Strings are anagram of each other using basic Java

I would go for something simpler to reason about: two strings are anagrams if, once sorted, they match exactly.
So in Java it would be something like:

    String s1 = "cat";
String s2 = "tac";
boolean isAnagram = false;
if (s1.length() == s2.length()) {
char[] s1AsChar = s1.toCharArray();
char[] s2AsChar = s2.toCharArray();
Arrays.sort(s1AsChar);
Arrays.sort(s2AsChar);
isAnagram = Arrays.equals(s1AsChar, s2AsChar);
}

finding if two words are anagrams of each other

Count the frequency of each character in the two strings. Check if the two histograms match. O(n) time, O(1) space (assuming ASCII) (Of course it is still O(1) space for Unicode but the table will become very large).

How can I check if two strings are anagrams of each other?

You need to think through your conditional logic a bit more. The loop is on the right track, but if there is a letter in s1 that is NOT in s2, you should break out of this loop and print the "False" statement. Consider using a variable like all_s1_in_s2 = True and then setting that to false if you find a letter that doesn't match.

Some other tips:

  • for l in s1 will loop through string s1 giving you access to each letter in sequence as l - you don't need range or len at all

  • The if .. in statement can help test whether a letter exists in a string, e.g. if letter in mystring: is a valid statement and this could help you a lot, again not needing range or len

  • You should avoid using numbers in variable names where possible - better would be word_one and word_two, as an example

Check whether two strings are anagrams

One way to do it is:

s1 = "elbow"
s2 = "below"

is_anagram <- function(s1, s2){
s1_sorted <- sort(strsplit(s1, "")[[1]])
s2_sorted <- sort(strsplit(s2, "")[[1]])
identical(s1_sorted, s2_sorted)
}

#> is_anagram(s1, s2)
#> [1] TRUE


Related Topics



Leave a reply



Submit