Frequency Counter Pattern — Swift

Sudarshan Sharma
2 min readNov 25, 2020

--

This pattern is used to count frequencies of values appearing in a string or array.

Let’s see how this pattern works.

Example 1

Create a function called same, which accepts two arrays. The function should return true if every value in the array has it's corresponding value squared in the second array. The frequency of values must also be the same.

func same(_ nums1: [Int], _ nums2: [Int]) -> Bool {
if nums1.count != nums2.count || nums1.isEmpty || nums2.isEmpty {
return false
}
var dict1 = [Int: Int]()
var dict2 = [Int: Int]()
nums1.forEach { num in
dict1[num] = dict1[num] != nil ? dict1[num]! + 1 : 1
}
nums2.forEach { num in
dict2[num] = dict2[num] != nil ? dict2[num]! + 1 : 1
}
for key in dict1.keys {
let doubleValue = key*key
if dict2[doubleValue] == nil || (dict2[doubleValue] != nil && dict2[doubleValue]! > 1) {
return false
}
}
return true
}
same([1, 2, 3], [4, 1, 9]) // true
same([1, 2, 3], [1, 9]) // false
same([1, 2, 1], [4, 4, 1]) // false (must be same frequency)

Example 2

Create a function called validAnagram to determine if the second string is an anagram of the first. An anagram is a word, phrase or name formed by rearranging the letters of another string, such as cinema formed from iceman.

func isValidAnagram(s1: String, s2: String) -> Bool {
if s1.count != s2.count {
return false
}
var dict1 = [Character: Int]()
var dict2 = [Character: Int]()
s1.forEach { char in
dict1[char] = dict1[char] != nil ? dict1[char]! + 1 : 1
}
s2.forEach { char in
dict2[char] = dict2[char] != nil ? dict2[char]! + 1 : 1
}
for key in dict1.keys {
if dict2[key] == nil || (dict2[key] != nil && dict2[key]! != dict1[key]) {
return false
}
}
return true
}
isValidAnagram(s1: "aaz", s2: "zza") // false
isValidAnagram(s1: "anagram", s2: "nagaram") // true
isValidAnagram(s1: "rat", s2: "car") // false
isValidAnagram(s1: "texttwisttime", s2: "timetwisttext") // true

--

--

Sudarshan Sharma
Sudarshan Sharma

No responses yet