Write a function

ocaml
#1

I need to write a function that takes two lists (list1, list2) and returns true if the lists are anagrams.
Two lists are anagrams if the elements from one may be rearranged to get the
other.

0 Likes

#2

An easy-to-write solution (O(n log n)) would be to sort both lists and check whether the results are equal.

let anagram l1 l2 =
  List.sort compare l1 = List.sort compare l2

Another way (maybe faster, I still have not computed the complexity) would be to go through l1 and making an associative list or a map counting the items, and going through l2 and doing the same, and checking the results. Or making a multi-set with all the elements from the first list, and removing them one by one when reading them in the second list… There are plenty of possibilities.

0 Likes