iOS Interview - Leetcode 242. Valid Anagram

May 05, 20241 min read#swift, #interview, #leetcode

Leetcode: 242. Valid Anagram

  • Primary idea: Compare the character freequencies of the 2 arrays
  • Time Complexity: O(n)
  • Space Complexity: O(n)
func isAnagram(_ s: String, _ t: String) -> Bool {
    guard s.count == t.count else { return false }

    var dict = [Character: Int]()

    for char in s {
        dict[char, default: 0] += 1
    }

    for char in t {
        if let count = dict[char], count > 0 {
            dict[char] = count - 1
        } else {
            return false
        }
    }

    return true
}

print(isAnagram("anagram", "nagaram")) // true
print(isAnagram("rat", "car")) // false
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024