Last active
September 15, 2023 23:39
-
-
Save lingoslinger/2dd972ba1a497e14b59ea2a18bd28a26 to your computer and use it in GitHub Desktop.
Swift: Most frequently occurring character in a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// I publicly share any answers to "coding challenges" I receive as a part of the interview process | |
// copy/paste this into an Xcode playground or the code challenge repl of choice | |
// Write a function in Swift that takes in a string as input and returns the most frequently occurring character in the string. | |
// If multiple characters have the same highest frequency, return any one of them. | |
func frequency(_ input: String) -> Character { | |
let charFrequency = input.reduce(into: [:]) {counts, char in | |
counts[char, default: 0] += 1 | |
} | |
let maxFrequency = charFrequency.values.max() | |
let mostFrequentChars = charFrequency.filter {$0.value == maxFrequency} | |
return mostFrequentChars.keys.first ?? Character("0") | |
} | |
print(frequency("testorama")) | |
// a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment