I cheated on this easy problem a little bit by looking at the suggested hints.
My first approach is by generating unique list of permutations of the input string but it exceeded the time limit when the input string is even just 10 characters long.
The idea for this problem is to count the number of characters and observe. For even length input (inputString.length % 2 == 0), then all characters should have even number of occurences. For odd, one character should have exactly 1 occurence only.
class Solution {
fun canPermutePalindrome(s: String): Boolean {
var charCount = IntArray(94)
s.forEach {
charCount[it - '!']++
}
return when {
s.length % 2 == 0 -> charCount.all { it % 2 == 0}
else -> charCount.filter { it % 2 != 0 }.count() == 1
}
}
}
Runtime: 116 ms, faster than 100.00% of Kotlin online submissions for Palindrome Permutation.
Memory Usage: 31.3 MB, less than 100.00% of Kotlin online submissions for Palindrome Permutation.