Hackernoon logoHow to Use Kotlin to Solve Coding Problems by@savjolovs

How to Use Kotlin to Solve Coding Problems

Vadims Savjolovs Senior Software Engineer @ Facebook explains how to use Kotlin to solve coding problems on Leetcode in Java. He explains how Kotlin can be used to solve algorithmic problems under time pressure in Android app development. He also explains how the language is more powerful than Java 6 and how much boilerplate code he needs to write to solve problems with Kotlin. He says that Kotlin provides an ability to iterate from the greater number down to the smaller number using the language's loops.
Vadims Savjolovs Hacker Noon profile picture

@savjolovsVadims Savjolovs

Senior Software Engineer @ Facebook

I have talked to many Android developers, and most of them are excited about Kotlin. So am I. When I just started learning Kotlin, I was solving Kotlin Koans, and along with other great features, I was impressed with the power of functions for performing operations on collections. Since then, I spent three years writing Kotlin code but rarely utilised all the potential of the language.

During this year, I did more than a hundred coding problems on Leetcode in Java. I didn’t switch to Kotlin because I know the syntax of Java 6 so well, that I could effortlessly write code without autocompletion and syntax highlighting. But I didn’t keep track of new Java features, as Android support of Java SDK lagged many versions behind. I didn’t switch to Kotlin for solving problems right away.

Although I was writing Kotlin code for several years, I felt that I need to make an extra cognitive effort to get the syntax and the language constructions right. Solving algorithmic problems, especially under time pressure, is very different from Android app development. Still, the more I learned about Kotlin, the more I realised how many powerful features I’m missing, and how much boilerplate code I need to write.

One day, I have decided that I need to move on, so I started a new session in Leetcode and switched the compiler to Kotlin. I solved just a few easy problems, but I already feel that I have something to share.


Let’s start with loops. Let’s say, you have an 

 of 10 elements 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
 and you want to print 

val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in (1 until array.size)) {

(1 until array.size)
 is an 
, a class that represents a range of values of type 
. The first element in this range is 
 and the last one is 
 as we used 
 to exclude the last value. We don’t want to get 

But what if we want to print all the elements of the array, except the element at index 5? Like this 

. Let’s get a bit more Kotliney then writing an 
 statement in the loop.

val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in array.indices - 5) {

 returns the range of valid indices for the array. In this case 
. Making 
(0..9) - 5
 will result in 
[0, 1, 2, 3, 4, 6, 7, 8, 9]
. This is exactly what we need.

Kotlin also provides an ability to iterate from the greater number down to the smaller number using 

. The iteration step size can also be changed using 

val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in array.size - 1 downTo 1 step 2) {

The code above with result in 


Remove Vowels from a String

It’s problem number 1119 on Leetcode.

Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.

Even in Java there is a 1 line regex solution, but my intuition was the following:

1. Create a StringBuilder

2. Iterate over characters, and if the current character is not a vowel, append it to the StringBuilder

3. Return String from the StringBuilder

public String removeVowels(String S) {
  StringBuilder sb = new StringBuilder();  
  for(char s: S.toCharArray()) {
    if(s != 'a' && s != 'e' && s != 'i' && s !='o' && s != 'u') {
  return sb.toString();

What about Kotlin? More idiomatic way is to use 


fun removeVowels(S: String): String {
  val vowels = setOf('a', 'e', 'i', 'o', 'u')
  return S.filter { it !in vowels }

filter {predicate: (Char) -> Boolean}
 returns a string containing only those characters from the original string that match the given predicate.

But instead of inverting 

 let’s use 

fun removeVowels(S: String): String {
  val vowels = setOf('a', 'e', 'i', 'o', 'u')
  return S.filterNot { it in vowels }

That was simple even for a beginner. Let’s move on to something a bit more sophisticated.

Running Sum of 1d Array

It’s another easy problem from Leetcode. Number 1480.

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums.

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

So we need to iterate over the array, adding the value at the current index to the running sum, and put it to the same index in the result array.

Is there something in Kotlin to help us with the running sum? Well, there’s different variations of 


Here’s a good explanation of those functions. But since Kotlin 1.4 there’s even more: 

. As we want to start with the first element and return an array, it looks like 
 is what we need. Let’s check its signature.

 * Returns a list containing successive accumulation values generated by applying [operation] from left to right
 * to each element and current accumulator value that starts with the first element of this array.
 * @param [operation] function that takes current accumulator value and an element, and calculates the next accumulator value.
 * @sample samples.collections.Collections.Aggregates.runningReduce
public inline fun IntArray.runningReduce(operation: (acc: Int, Int) -> Int): List<Int>

Sounds a bit too complex, but it will make sense when you’ll see an example.

fun runningSum(nums: IntArray): IntArray {
  return nums.runningReduce { sum, element -> sum + element }.toIntArray()

This is the whole solution to the running sum problem using Kotlin 

 starts with the first
in the array, element represens the current element. In lambda, we calculate the value of the next 
. Oh… I guess my explanation isn’t making it more clear that a doc. Let’s just print out the values of the 
 and the 
 at each step:

sum: 1; element: 2; sum + element: 3
sum: 3; element: 3; sum + element: 6
sum: 6; element: 4; sum + element: 10
sum: 10; element: 5; sum + element: 15

And the array we return is 

[1, 3, 6, 10, 15]
. There is no 
sum + element: 1
, I didn’t miss the line. The thing is that 
, as we see in the doc, takes the first value as the initial accumulator.

Unfortunately, Leetcode doesn’t support Kotlin 1.4 yet, so the code above might not compile.

Most Common Word

Easy Leetcode problem, number 819.

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn’t banned, and that the answer is unique.

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
Output: "ball"

What are the steps to solve it?

1. Convert string to lower case and split by words.

[bob, hit, a, ball, the, hit, ball, flew, far, after, it, was, hit]

2. Create a set of banned words.


3. Create a map of words to their occurrence, excluding the banned words.

{bob=1, a=1, ball=2, the=1, flew=1, far=1, after=1, it=1, was=1}

4. Return word with the highest number of occurrences from the map.


Let’s implement those 4 steps in Java.

public String mostCommonWord(String paragraph, String[] banned) {
  // 1. Covert string to lower case and split by words.
  String[] words = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase().split("\\s+");

  // 2. Create a set of banned words.
  Set<String> bannedWords = new HashSet();
  for (String word : banned)

  // 3. Create a map of words to their occurrence, excluding the banned words
  Map<String, Integer> wordCount = new HashMap();
  for (String word : words) {
    if (!bannedWords.contains(word))
      wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);

  // 4. Return word with the highest number of occurrences from the map.
  return Collections.max(wordCount.entrySet(), Map.Entry.comparingByValue()).getKey();

And the same 4 steps in Kotlin.

fun mostCommonWord(paragraph: String, banned: Array<String>): String {
  // 1. Covert string to lower case and split by words.
  val words = paragraph.toLowerCase().split("\\W+|\\s+".toRegex())
  // 2. Create a set of banned words.
  val bannedSet = banned.toHashSet()
  // 3. Create a map of words to their occurrence, excluding the banned words
  val wordToCount = words.filterNot { it in bannedSet }.groupingBy { it }.eachCount()
  // 4. Return word with the highest number of occurrences from the map.
  return wordToCount.maxBy { it.value }!!.key

Now let’s go through the functions to see what is happening here.

1. We split the string into 

words: List<String>
. The type is inferred.
2. Converting 
banned: Array<String>
 to make 
 checks in O(1) time
3. In this step, we chain 3 function calls. First, we use 
 to filter out banned words. 
filterNot { it in banned }
 will return a 
 that contains only those strings that are not in the 
 array. Unlike 
 that returns a map, 
 returns an object of 
 type, that could be used later with one of group-and-fold operations. We use it in 
 lambda. This means that we are grouping by the current element (word) in the collection. In other words — we create a map, where the key is a word, and the value is a count of occurrences of the word. To get the number of occurrences we use 
 on the 
4. We use 
 function to get the first largest element in the map, by 
. This returns us an object of 
Map.Entry<String, Int>?
, e.g. 
ball = 2
. And we return a key, which is the most common word in the sentence.

Order of elements

When you create a set using 

setOf(“a”, “b”, “c”)
 or converting array to set using 
arrayOf(“a”, “b”, “c”).toSet()
 the returned set is 
 and therefore element iteration order is preserved.

The same is true about maps

mapOf(Pair(“a”, 1), Pair(“b”, 2))
arrayOf(Pair(“a”, 1), Pair(“b”, 2)).toMap()

Both functions will return an instance of 

 that keeps preserves the original element order. Knowing it might be helpful when solving problems.

I have covered just a few of all available collection functions in Kotlin. There’s 

 and much more!


Join Hacker Noon

Create your free account to unlock your custom reading experience.