Coding Challenges in Kotlin
The challenges
| # | Problem | Idiomatic Kotlin tool |
|---|---|---|
| 1 | Reverse words in a sentence | split, reversed, joinToString |
| 2 | Is it a palindrome? | filter(Char::isLetterOrDigit), lowercase, reversed |
| 3 | Two Sum | a HashMap of value → index |
| 4 | First non-repeating character | groupingBy { it }.eachCount() |
| 5 | Anagram groups | groupBy { it.toCharArray().sorted() } |
| 6 | FizzBuzz with when | when with conditions |
| 7 | Count word frequencies, top 3 | groupingBy, sortedByDescending, take |
How to answer in Kotlin interviews
- Clarify: empty input? Case-sensitive? Unicode?
- Start with a clear solution, then make it idiomatic with the collection functions.
- State the time and space complexity; collection chains still count as O(n) passes.
- Mention trade-offs: chains are readable, while a single loop can be faster for huge data.
- Test with an edge case.
Showing Kotlin skill
- Use
val, immutable collections and expression bodies (fun f() = …). - Handle nulls with
?.,?:andfirstOrNull, never!!. - Use data classes for results, and
whenfor branching.
Where to practise
LeetCode (choose Kotlin), Kotlin Koans at play.kotlinlang.org, and Exercism's Kotlin track.
Example
fun reverseWords(s: String) = s.trim().split(Regex("\\s+")).reversed().joinToString(" ")
fun isPalindrome(s: String): Boolean {
val clean = s.filter(Char::isLetterOrDigit).lowercase()
return clean == clean.reversed()
}
fun twoSum(nums: IntArray, target: Int): Pair<Int, Int>? {
val seen = HashMap<Int, Int>() // value → index
nums.forEachIndexed { i, x ->
seen[target - x]?.let { return it to i }
seen[x] = i
}
return null
}
fun firstUnique(s: String): Char? {
val counts = s.groupingBy { it }.eachCount()
return s.firstOrNull { counts[it] == 1 }
}
fun anagramGroups(words: List<String>) =
words.groupBy { it.toCharArray().sorted() }.values.toList()
fun fizzBuzz(n: Int) = (1..n).map {
when {
it % 15 == 0 -> "FizzBuzz"
it % 3 == 0 -> "Fizz"
it % 5 == 0 -> "Buzz"
else -> it.toString()
}
}
fun topWords(text: String, k: Int) = text.lowercase().split(Regex("\\W+"))
.filter { it.isNotBlank() }
.groupingBy { it }.eachCount()
.entries.sortedByDescending { it.value }
.take(k).map { it.key to it.value }
fun main() {
println(reverseWords(" Kotlin is fun ")) // fun is Kotlin
println(isPalindrome("A man, a plan, a canal: Panama"))
println(twoSum(intArrayOf(2, 7, 11, 15), 9)) // (0, 1)
println(firstUnique("swiss")) // w
println(anagramGroups(listOf("eat", "tea", "tan", "ate", "nat")))
println(fizzBuzz(15).joinToString(" "))
println(topWords("the cat and the hat and the bat", 2)) // [(the, 3), (and, 2)]
}