I have an interview in Kotlin so I’ve been trying to do some simple LeetCode problems in Kotlin but I find it difficult (I’m used to Python).
For example, given 242. Valid Anagram:
fun isAnagram(s: String, t: String): Boolean { if (s.length != t.length) return false val m = mutableMapOf<Char, Int>() s.forEach { c -> m[c] = m.getOrDefault(c, 0) + 1 } t.forEach { c -> if (!m.contains(c) || m[c]!! <= 0) { return false } m[c] = m[c]!! - 1 } return true }
I am struggling with map access because
- No defaultdict and I have to use getOrDefault instead of access by []
- Being forced to account for nullability (m[c]!!) but it does not feel clean at all
Another example, 49. Group Anagrams:
fun groupAnagrams(strs: Array<String>): List<List<String>> { val groups = mutableMapOf<String, MutableList<String>>() for (s in strs) { val key = s.toCharArray().sorted().joinToString("") if (groups[key] == null) groups[key] = mutableListOf() groups[key]!!.add(s) } return groups.values.toList() }
- Output is expecting a List<List<String>> but I have to compute with a bunch of “mutable” data structures
- No defaultdict (again)
- Having to convert ‘s’ to a CharArray before sorting and joining it
- Nullability again
- Converting map values toList
It just feels like a big hassle and that I’m fighting against the language. Is there a better way to think about these things?
submitted by /u/EvolvedPik
[link] [comments]