100 Kotlin practice problems with solutions

Tired of watching Kotlin tutorials and still feeling a little lost when it’s time to write your own code? That quiet frustration is something every developer knows—and it’s exactly what this post will help you shake off.

We’ve put together 100 Kotlin practice problems with warm, step-by-step solutions that feel like a friend guiding you. You’ll start gently with variables, loops, and functions, then move on to classes, collections, and the elegant features that make Kotlin feel so good to write. Each problem is explained in plain, friendly language so you can try it yourself first, then check the answer and truly understand the why behind the logic.

Practice is where real confidence is born—every small success makes you a little braver as a developer. Pick a problem, take a deep breath, and enjoy that beautiful “I really got this!” moment. You’re ready.

Also try it: 100 Java practice problems with solutions

1. Write a Kotlin function that takes two integers and returns their sum.

kotlin

fun sum(a: Int, b: Int): Int = a + b

2. Write a function that checks if a given number is even or odd.

kotlin

fun isEven(n: Int): Boolean = n % 2 == 0

3. Write a function that returns the maximum of three integers.

kotlin

fun maxOfThree(a: Int, b: Int, c: Int): Int = maxOf(a, maxOf(b, c))

4. Convert a string to uppercase using a built-in function.

kotlin

fun toUpperCase(str: String): String = str.uppercase()

5. Write a function that returns the length of a string.

kotlin

fun stringLength(str: String): Int = str.length

6. Write a function that takes a string and returns the same string reversed.

kotlin

fun reverseString(str: String): String = str.reversed()

7. Write a function that checks if a string is a palindrome.

kotlin

fun isPalindrome(s: String): Boolean = s == s.reversed()

8. Write a function that counts the number of vowels in a string.

kotlin

fun countVowels(str: String): Int = str.count { it in "aeiouAEIOU" }

9. Write a function that returns the factorial of a non-negative integer.

kotlin

fun factorial(n: Int): Long = if (n <= 1) 1 else n * factorial(n - 1)

10. Write a function that prints numbers from 1 to n using a for loop.

kotlin

fun printNumbers(n: Int) {
    for (i in 1..n) println(i)
}

11. Write a function that sums all elements in a list of integers.

kotlin

fun sumList(list: List<Int>): Int = list.sum()

12. Write a function that returns the largest element in a list of integers.

kotlin

fun maxInList(list: List<Int>): Int = list.maxOrNull() ?: throw IllegalArgumentException("Empty list")

13. Write a function that returns the average of a list of doubles.

kotlin

fun average(list: List<Double>): Double = if (list.isEmpty()) 0.0 else list.sum() / list.size

14. Write a function that filters even numbers from a list returning only odds.

kotlin

fun filterOdds(list: List<Int>): List<Int> = list.filter { it % 2 != 0 }

15. Write a function that squares each element in a list and returns a new list.

kotlin

fun squareList(list: List<Int>): List<Int> = list.map { it * it }

16. Write a function that counts how many times a given word appears in a list of strings.

kotlin

fun countWordOccurrences(words: List<String>, target: String): Int = words.count { it == target }

17. Write a function that removes duplicates from a list.

kotlin

fun removeDuplicates(list: List<Int>): List<Int> = list.distinct()

18. Write a function that groups a list of strings by their first character.

kotlin

fun groupByFirstChar(words: List<String>): Map<Char, List<String>> = words.groupBy { it.firstOrNull() ?: ' ' }

19. Write a function that checks if a list contains a specific element using a lambda.

kotlin

fun containsElement(list: List<Int>, element: Int): Boolean = list.any { it == element }

20. Write a function that returns the first element of a list that satisfies a predicate.

kotlin

fun findFirstEven(list: List<Int>): Int? = list.find { it % 2 == 0 }

21. Write a function that returns a map where keys are integers and values are their square.

kotlin

fun squaresMap(n: Int): Map<Int, Int> = (1..n).associate { it to it * it }

22. Write a function that merges two maps, summing values for common keys.

kotlin

fun mergeMaps(map1: Map<String, Int>, map2: Map<String, Int>): Map<String, Int> =
    (map1.keys + map2.keys).associateWith { key -> map1.getOrDefault(key, 0) + map2.getOrDefault(key, 0) }

23. Write a function that finds the most frequent element in a list.

kotlin

fun mostFrequent(list: List<Int>): Int? = list.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key

24. Write a function that returns the intersection of two lists.

kotlin

fun intersect(list1: List<Int>, list2: List<Int>): List<Int> = list1.intersect(list2).toList()

25. Write a function that returns the union of two lists (no duplicates).

kotlin

fun union(list1: List<Int>, list2: List<Int>): List<Int> = (list1 + list2).distinct()

26. Write a function that rotates a list to the left by k positions.

kotlin

fun rotateLeft(list: List<Int>, k: Int): List<Int> {
    if (list.isEmpty()) return list
    val shift = k % list.size
    return list.drop(shift) + list.take(shift)
}

27. Write a function that converts a list of strings to a single string separated by commas.

kotlin

fun joinWithComma(strings: List<String>): String = strings.joinToString(",")

28. Write a function that returns the Fibonacci sequence up to n terms.

kotlin

fun fibonacci(n: Int): List<Int> {
    if (n <= 0) return emptyList()
    if (n == 1) return listOf(0)
    val list = mutableListOf(0, 1)
    while (list.size < n) {
        list.add(list.last() + list[list.size - 2])
    }
    return list
}

29. Write a function that checks if a number is prime.

kotlin

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    for (i in 2..Math.sqrt(n.toDouble()).toInt()) {
        if (n % i == 0) return false
    }
    return true
}

30. Write a function that prints a pyramid pattern for a given height.

kotlin

fun printPyramid(height: Int) {
    for (i in 1..height) {
        println(" ".repeat(height - i) + "*".repeat(2 * i - 1))
    }
}

31. Write a function that reads a line from standard input and prints it back.

kotlin

fun echoInput() {
    val input = readlnOrNull() ?: return
    println(input)
}

32. Write a function that reads integers until the user enters 0 and returns the sum.

kotlin

fun sumUntilZero(): Int {
    var sum = 0
    while (true) {
        val input = readlnOrNull()?.toIntOrNull() ?: break
        if (input == 0) break
        sum += input
    }
    return sum
}

33. Write a data class Person with properties name and age, and create an instance.

kotlin

data class Person(val name: String, val age: Int)

fun main() {
    val person = Person("Alice", 30)
    println(person)
}

34. Write a function that uses a when expression to return the type of a number: “Positive”, “Negative”, or “Zero”.

kotlin

fun numberType(n: Int): String = when {
    n > 0 -> "Positive"
    n < 0 -> "Negative"
    else -> "Zero"
}

35. Write a function that returns the last element of a list or null if empty.

kotlin

fun <T> lastOrNull(list: List<T>): T? = list.lastOrNull()

36. Write an extension function isEven for Int.

kotlin

fun Int.isEven(): Boolean = this % 2 == 0

37. Write a function that uses a lambda to sort a list of strings by their length.

kotlin

fun sortByLength(strings: List<String>): List<String> = strings.sortedBy { it.length }

38. Write a function that takes a nullable string and returns its length or 0 if null.

kotlin

fun lengthOrDefault(str: String?): Int = str?.length ?: 0

39. Write a function that safely divides two integers, returning null if division by zero.

kotlin

fun safeDivide(a: Int, b: Int): Int? = if (b == 0) null else a / b

40. Write a function that uses takeWhile to get the prefix of a list until a condition fails.

kotlin

fun takeUntilNegative(list: List<Int>): List<Int> = list.takeWhile { it >= 0 }

41. Write a function that flattens a list of lists into a single list.

kotlin

fun flatten(list: List<List<Int>>): List<Int> = list.flatten()

Also try it: 100 Swift practice problems with solutions

42. Write a function that returns the product of all elements in a list of integers (use fold).

kotlin

fun product(list: List<Int>): Int = list.fold(1) { acc, i -> acc * i }

43. Write a function that checks if two strings are anagrams.

kotlin

fun areAnagrams(s1: String, s2: String): Boolean = s1.lowercase().toCharArray().sorted() == s2.lowercase().toCharArray().sorted()

44. Write a function that removes all whitespace from a string.

kotlin

fun removeWhitespace(str: String): String = str.replace("\\s".toRegex(), "")

45. Write a function that capitalizes the first letter of each word in a sentence.

kotlin

fun capitalizeWords(sentence: String): String = sentence.split(" ").joinToString(" ") { word -> word.replaceFirstChar { it.uppercase() } }

46. Write a function that returns the number of words in a sentence (words separated by spaces).

kotlin

fun wordCount(sentence: String): Int = sentence.split(" ").filter { it.isNotBlank() }.size

47. Write a function that generates a random integer between min and max (inclusive).

kotlin

import kotlin.random.Random

fun randomInt(min: Int, max: Int): Int = Random.nextInt(min, max + 1)

48. Write a function that implements a simple FizzBuzz for numbers 1..100.

kotlin

fun fizzBuzz() {
    for (i in 1..100) {
        when {
            i % 15 == 0 -> println("FizzBuzz")
            i % 3 == 0 -> println("Fizz")
            i % 5 == 0 -> println("Buzz")
            else -> println(i)
        }
    }
}

49. Write a function that returns the GCD (greatest common divisor) of two numbers.

kotlin

fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

50. Write a function that returns the LCM of two numbers.

kotlin

fun lcm(a: Int, b: Int): Int = a / gcd(a, b) * b

51. Write a function that creates a read-only list of 5 elements and tries to modify it (demonstrate immutable).

kotlin

fun immutableList() {
    val list = listOf(1, 2, 3, 4, 5)
    // list.add(6) // Compilation error
    println(list)
}

52. Write a function that swaps two elements in a mutable list by index.

kotlin

fun swap(list: MutableList<Int>, i: Int, j: Int) {
    val temp = list[i]
    list[i] = list[j]
    list[j] = temp
}

53. Write a function that returns the difference between the largest and smallest element in a list.

kotlin

fun range(list: List<Int>): Int = list.maxOrNull()!! - list.minOrNull()!!

54. Write a function that counts the frequency of characters in a string.

kotlin

fun charFrequency(str: String): Map<Char, Int> = str.groupingBy { it }.eachCount()

55. Write a function that checks if a year is a leap year.

kotlin

fun isLeapYear(year: Int): Boolean = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

56. Write a function that returns the current date and time in “YYYY-MM-DD HH:MM:SS” format.

kotlin

import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

fun currentDateTime(): String {
    val now = LocalDateTime.now()
    return now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
}

57. Write a function that reads a file by name and prints its lines.

kotlin

import java.io.File

fun printFileContent(fileName: String) {
    val file = File(fileName)
    if (file.exists()) {
        file.readLines().forEach { println(it) }
    } else {
        println("File not found")
    }
}

58. Write a function that writes a list of strings to a file, one per line.

kotlin

fun writeLinesToFile(fileName: String, lines: List<String>) {
    File(fileName).writeText(lines.joinToString("\n"))
}

59. Write a function that uses run to perform multiple operations on a StringBuilder.

kotlin

fun buildStringWithRun(): String = StringBuilder().run {
    append("Hello")
    append(" ")
    append("World")
    toString()
}

60. Write a function that uses with to apply a block to a list.

kotlin

fun withExample(): List<Int> = with(mutableListOf(1, 2, 3)) {
    add(4)
    add(5)
    this
}

61. Write a function that demonstrates the use of lateinit for a variable.

kotlin

class LateInitDemo {
    lateinit var message: String

    fun setMessage(msg: String) {
        message = msg
    }

    fun printMessage() {
        if (::message.isInitialized) println(message) else println("Not initialized")
    }
}

62. Write a function that returns a Pair of the first two elements of a list.

kotlin

fun firstTwo(list: List<Int>): Pair<Int?, Int?> = Pair(list.getOrNull(0), list.getOrNull(1))

63. Write a function that uses a sealed class to represent different operation results.

kotlin

sealed class Result
data class Success(val data: String) : Result()
data class Error(val message: String) : Result()

fun handleResult(result: Result) = when (result) {
    is Success -> println("Success: ${result.data}")
    is Error -> println("Error: ${result.message}")
}

64. Write a function that uses require to validate a positive number.

kotlin

fun squarePositive(n: Int): Int {
    require(n > 0) { "Number must be positive" }
    return n * n
}

**65. Write a function that implements a simple calculator using when for operations +, -, , /.*

kotlin

fun calculator(a: Double, b: Double, op: Char): Double = when (op) {
    '+' -> a + b
    '-' -> a - b
    '*' -> a * b
    '/' -> if (b != 0.0) a / b else throw IllegalArgumentException("Division by zero")
    else -> throw IllegalArgumentException("Unknown operator")
}

66. Write a function that returns the index of the first occurrence of a substring, using indexOf.

kotlin

fun firstOccurrence(str: String, sub: String): Int = str.indexOf(sub)

67. Write a function that splits a string by a delimiter and returns a list.

kotlin

fun splitString(str: String, delimiter: String): List<String> = str.split(delimiter)

68. Write a function that uses reduce to concatenate all strings in a list.

kotlin

fun concatenate(strings: List<String>): String = strings.reduce { acc, s -> acc + s }

69. Write a function that converts a list to a set (remove duplicates).

kotlin

fun toSet(list: List<Int>): Set<Int> = list.toSet()

70. Write a function that uses chunked to split a list into sublists of size 3.

kotlin

fun chunkByThree(list: List<Int>): List<List<Int>> = list.chunked(3)

71. Write an extension function isNotEmptyBlank for String that returns true if not null or blank.

kotlin

fun String?.isNotEmptyBlank(): Boolean = !this.isNullOrBlank()

72. Write a function that uses a Sequence to process large data lazily.

kotlin

fun lazyProcessing() {
    val numbers = generateSequence(1) { it + 1 }
    val firstTen = numbers.take(10).toList()
    println(firstTen)
}

73. Write a function that finds the second largest element in an array.

kotlin

fun secondLargest(arr: List<Int>): Int? {
    val sorted = arr.distinct().sortedDescending()
    return sorted.getOrNull(1)
}

74. Write a function that returns a list of prime numbers up to n using a simple sieve.

kotlin

fun primesUpTo(n: Int): List<Int> {
    val sieve = BooleanArray(n + 1) { true }
    sieve[0] = false
    if (n >= 1) sieve[1] = false
    var i = 2
    while (i * i <= n) {
        if (sieve[i]) {
            for (j in i * i..n step i) sieve[j] = false
        }
        i++
    }
    return sieve.indices.filter { sieve[it] }
}

75. Write a function that rotates an array to the right by k positions.

kotlin

fun rotateRight(list: List<Int>, k: Int): List<Int> {
    if (list.isEmpty()) return list
    val shift = k % list.size
    return list.takeLast(shift) + list.dropLast(shift)
}

76. Write a function that finds all indices where a given value occurs in a list.

kotlin

fun indicesOf(list: List<Int>, value: Int): List<Int> = list.indices.filter { list[it] == value }

77. Write a function that checks if a number is a perfect number (sum of divisors equals itself).

kotlin

fun isPerfectNumber(n: Int): Boolean {
    if (n <= 1) return false
    var sum = 0
    for (i in 1 until n) {
        if (n % i == 0) sum += i
    }
    return sum == n
}

78. Write a function that converts a binary string to an integer.

kotlin

fun binaryToInt(binary: String): Int = binary.toInt(2)

79. Write a function that generates a multiplication table for a given number up to 10.

kotlin

fun multiplicationTable(n: Int) {
    for (i in 1..10) {
        println("$n x $i = ${n * i}")
    }
}

80. Write a function that returns the sum of digits of a positive integer.

kotlin

fun sumOfDigits(n: Int): Int = n.toString().map { it.digitToInt() }.sum()

81. Write a function that reverses an array in place.

kotlin

fun reverseInPlace(arr: MutableList<Int>) {
    var i = 0
    var j = arr.lastIndex
    while (i < j) {
        val temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
        i++
        j--
    }
}

82. Write a function that implements a simple fold to compute the maximum element.

kotlin

fun maxWithFold(list: List<Int>): Int? = list.fold(null) { acc, i -> if (acc == null || i > acc) i else acc }

83. Write a function that uses zip to combine two lists into a list of pairs.

kotlin

fun zipLists(a: List<Int>, b: List<Int>): List<Pair<Int, Int>> = a.zip(b)

84. Write a function that sorts a list of strings ignoring case.

kotlin

fun sortIgnoreCase(strings: List<String>): List<String> = strings.sortedWith(String.CASE_INSENSITIVE_ORDER)

85. Write a function that partitions a list into two lists based on a predicate.

kotlin

fun partitionList(list: List<Int>, predicate: (Int) -> Boolean): Pair<List<Int>, List<Int>> = list.partition(predicate)

86. Write a function that returns the Cartesian product of two lists (all pairs).

kotlin

fun cartesianProduct(a: List<Int>, b: List<Int>): List<Pair<Int, Int>> = a.flatMap { i -> b.map { j -> i to j } }

87. Write a function that removes every n‑th element from a list.

kotlin

fun removeEveryNth(list: List<Int>, n: Int): List<Int> = list.filterIndexed { index, _ -> (index + 1) % n != 0 }

88. Write a function that computes the mode of a list (most frequent element).

kotlin

fun mode(list: List<Int>): Int? = list.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key

89. Write a function that generates all substrings of a string.

kotlin

fun allSubstrings(str: String): List<String> {
    val result = mutableListOf<String>()
    for (i in str.indices) {
        for (j in i + 1..str.length) {
            result.add(str.substring(i, j))
        }
    }
    return result
}

90. Write a function that validates an email address using a simple regex.

kotlin

fun isValidEmail(email: String): Boolean = Regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$").matches(email)

91. Write a function that uses a tailrec function to compute factorial.

kotlin

tailrec fun tailrecFactorial(n: Int, accumulator: Long = 1): Long = if (n <= 1) accumulator else tailrecFactorial(n - 1, n * accumulator)

92. Write a function that finds the longest increasing subsequence length (not the subsequence).

kotlin

fun lisLength(nums: List<Int>): Int {
    if (nums.isEmpty()) return 0
    val dp = IntArray(nums.size) { 1 }
    for (i in nums.indices) {
        for (j in 0 until i) {
            if (nums[j] < nums[i]) {
                dp[i] = maxOf(dp[i], dp[j] + 1)
            }
        }
    }
    return dp.maxOrNull() ?: 0
}

93. Write a function that finds the first non‑repeating character in a string.

kotlin

fun firstNonRepeating(str: String): Char? {
    val count = str.groupingBy { it }.eachCount()
    return str.find { count[it] == 1 }
}

94. Write a function that checks if a string contains only digits.

kotlin

fun isDigitsOnly(str: String): Boolean = str.all { it.isDigit() }

95. Write a function that returns a random element from a list (or null if empty).

kotlin

import kotlin.random.Random

fun randomElement(list: List<Int>): Int? = if (list.isNotEmpty()) list[Random.nextInt(list.size)] else null

Also try it: 100 Dart practice problems with solutions

96. Write a function that prints a diamond pattern for a given size.

kotlin

fun printDiamond(size: Int) {
    for (i in 1..size) {
        println(" ".repeat(size - i) + "*".repeat(2 * i - 1))
    }
    for (i in size - 1 downTo 1) {
        println(" ".repeat(size - i) + "*".repeat(2 * i - 1))
    }
}

97. Write a function that counts how many times a given digit appears in a number.

kotlin

fun countDigitOccurrence(number: Int, digit: Int): Int = number.toString().count { it.digitToInt() == digit }

98. Write a function that converts a number to its binary representation without using built‑in toString(2).

kotlin

fun toBinary(n: Int): String {
    var num = n
    val sb = StringBuilder()
    do {
        sb.append(num % 2)
        num /= 2
    } while (num > 0)
    return sb.reverse().toString()
}

99. Write a function that creates an inline class for a non‑empty string.

kotlin

@JvmInline
value class NonEmptyString(private val value: String) {
    init {
        require(value.isNotBlank()) { "String cannot be blank" }
    }
    fun getValue(): String = value
}

100. Write a function that uses a coroutine to delay and print a message.

kotlin

import kotlinx.coroutines.*

suspend fun delayedPrint() {
    delay(1000)
    println("Hello after 1 second")
}

fun main() = runBlocking {
    delayedPrint()
}

Final Thoughts

And there you have it — 100 Kotlin practice problems walked through, step by step, with you in mind. If you made it to the end (or even halfway!), take a moment and be genuinely proud of yourself. You didn’t just read about Kotlin — you showed up, got your hands dirty, and grew a little with every problem.

The truth is, real programming confidence isn’t born from watching. It’s built quietly through doing, stumbling, fixing, and finally seeing your code run. Every challenge you solved here added a brick to that foundation. The cozy syntax, the smart null safety, the expressive functions — they all start to feel like home once you practice enough.

Keep the momentum going. Revisit any problem that felt tricky, push yourself to build mini projects, or even teach a friend what you just learned. Every small step counts.

Thanks for trusting this collection with your time. Bookmark it, share it, and whenever doubt creeps back in, come solve a few more. You’re already a better Kotlin developer than you were when you started — and you’re only going to get better from here. Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top