Skip to content

Instantly share code, notes, and snippets.

@godrm
Created April 16, 2018 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save godrm/63fd06bba53484a92138c6449ec05d51 to your computer and use it in GitHub Desktop.
Save godrm/63fd06bba53484a92138c6449ec05d51 to your computer and use it in GitHub Desktop.
func countByCharacter(_ value: String) -> [Character: Int] {
var countMap = [Character: Int]()
for char in value {
let count = countMap[char] ?? 0
countMap[char] = count + 1
}
return countMap
}
func isValid(_ countMap: [Character:Int]) -> Bool {
let allKeys = countMap.keys
var compareMap = [Int:Int]()
for key in allKeys {
let value = countMap[key] ?? 0
let count = compareMap[value] ?? 0
compareMap[value] = count + 1
}
let countKeys = compareMap.keys
let minKey = countKeys.min() ?? 0
let maxKey = countKeys.max() ?? 0
let keyDiff = maxKey - minKey
let maxValue = compareMap[maxKey] ?? 0
let lastOne = (compareMap[minKey] ?? 0)==1 && minKey==1
return (compareMap.count == 1
|| (compareMap.count == 2 && keyDiff == 1 && maxValue == 1)
|| (compareMap.count == 2 && lastOne))
}
@MrRochito
Copy link

Thank you @godrm 👍 great solution. I can't solve the problem by myself after getting the dictionary with the count with each character.

HackerRank Problem:

Swift Solution there:

import Foundation

// Complete the isValid function below.
func isValid(s: String) -> String {
    var countMap = [Character: Int]()
    for char in s {
        let count = countMap[char] ?? 0
        countMap[char] = count + 1
    }

    let allKeys = countMap.keys
    var compareMap = [Int:Int]()
    for key in allKeys {
        let value = countMap[key] ?? 0
        let count = compareMap[value] ?? 0
        compareMap[value] = count + 1
    }
    let countKeys = compareMap.keys
    let minKey = countKeys.min() ?? 0
    let maxKey = countKeys.max() ?? 0
    let keyDiff = maxKey - minKey
    let maxValue = compareMap[maxKey] ?? 0
    let lastOne = (compareMap[minKey] ?? 0)==1 && minKey==1
  
  let returnedValue: String = (compareMap.count == 1
  || (compareMap.count == 2 && keyDiff == 1 && maxValue == 1)
  || (compareMap.count == 2 && lastOne)) ? "YES" : "NO"
  return returnedValue
}

let stdout = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
FileManager.default.createFile(atPath: stdout, contents: nil, attributes: nil)
let fileHandle = FileHandle(forWritingAtPath: stdout)!

guard let s = readLine() else { fatalError("Bad input") }

let result = isValid(s: s)

fileHandle.write(result.data(using: .utf8)!)
fileHandle.write("\n".data(using: .utf8)!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment