Function to Determine if Two Strings are Anagrams

An anagram is rearranging letters of words or phrases to create new words or phrases. For example, “debit card” and “bad credit” are anagrams of each other.

func isAnagram(s1: String, s2: String) -> Bool {
    var counts = [Character: Int]()

for c in s1 {
        let count = counts[c] ?? 0
        counts[c] = count + 1
    }

for c in s2 {
        let count = counts[c] ?? 0

if count <= 0 {
            return false
        }

counts[c] = count - 1
    }

for (_, count) in counts {
        if count != 0 {
            return false
        }
    }

return true
}

Test Cases

  • isAnagram(s1:"elvis", s2:"lives")
  • isAnagram(s1:"eleven plus two", s2:"twelve plus one")
  • isAnagram(s1:"debit card", s2:"bad credit")
  • isAnagram(s1:"abc", s2:"123")
  • isAnagram(s1:"cinema", s2:"iceman")