Skip to content

Instantly share code, notes, and snippets.

@jrraymond
Last active August 29, 2015 13:58
Show Gist options
  • Save jrraymond/10001907 to your computer and use it in GitHub Desktop.
Save jrraymond/10001907 to your computer and use it in GitHub Desktop.
Tests whether two strings are anagrams in O(n) time.
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Foldable
isAnagram :: [Char] -> [Char] -> Bool
isAnagram xs ys = f xs ys Map.empty
where
f :: [Char] -> [Char] -> Map Char Int -> Bool
f (x:xs) ys m = if x `Map.member` m
then f xs ys (Map.update (Just . (+1)) x m)
else f xs ys (Map.insert x 1 m)
f [] (y:ys) m = if y `Map.member` m
then f [] ys (Map.update (Just . (+(-1))) y m)
else False
f [] [] m = foldMap (All . (== 0)) m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment