Kotlin · Module 8 · Lesson 21 min read

Coding Challenges in Kotlin

The challenges

#ProblemIdiomatic Kotlin tool
1Reverse words in a sentencesplit, reversed, joinToString
2Is it a palindrome?filter(Char::isLetterOrDigit), lowercase, reversed
3Two Suma HashMap of value → index
4First non-repeating charactergroupingBy { it }.eachCount()
5Anagram groupsgroupBy { it.toCharArray().sorted() }
6FizzBuzz with whenwhen with conditions
7Count word frequencies, top 3groupingBy, sortedByDescending, take

How to answer in Kotlin interviews

  1. Clarify: empty input? Case-sensitive? Unicode?
  2. Start with a clear solution, then make it idiomatic with the collection functions.
  3. State the time and space complexity; collection chains still count as O(n) passes.
  4. Mention trade-offs: chains are readable, while a single loop can be faster for huge data.
  5. Test with an edge case.

Showing Kotlin skill

  • Use val, immutable collections and expression bodies (fun f() = …).
  • Handle nulls with ?., ?: and firstOrNull, never !!.
  • Use data classes for results, and when for branching.

Where to practise

LeetCode (choose Kotlin), Kotlin Koans at play.kotlinlang.org, and Exercism's Kotlin track.

Example

kotlin
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)]
}