paint-brush
How to Use Kotlin to Solve Coding Problemsby@savjolovs
1,111 reads
1,111 reads

How to Use Kotlin to Solve Coding Problems

by Vadims SavjolovsNovember 9th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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.

Company Mentioned

Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - How to Use Kotlin to Solve Coding Problems
Vadims Savjolovs HackerNoon profile picture

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.

Loops

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

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

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

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

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

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

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

array.indices
 returns the range of valid indices for the array. In this case 
array.indices
 represent 
IntRange
 of 
(0..9)
. 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 

downTo
. The iteration step size can also be changed using 
step
.

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

The code above with result in 

97531
.

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') {
      sb.append(s);  
    }
  }
  return sb.toString();
}

What about Kotlin? More idiomatic way is to use 

filter()
 or 
filterNot()
.

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 

!in
 let’s use 
filterNot()

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 

fold()
 and 
reduce()
 operations.

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

runningFold()
 and 
runningReduce()
. As we want to start with the first element and return an array, it looks like 
runningReduce()
 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
 */
@SinceKotlin("1.4")
@kotlin.internal.InlineOnly
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 

runningReduce()
 function. 
sum
 starts with the first
element
in the array, element represens the current element. In lambda, we calculate the value of the next 
sum
. Oh… I guess my explanation isn’t making it more clear that a doc. Let’s just print out the values of the 
sum
 and the 
element
 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 
runningReduce
, 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.

Input:
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.

[hit]

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.

ball

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)
    bannedWords.add(word);

  // 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 
HashSet
 to make 
in
 checks in O(1) time
3. In this step, we chain 3 function calls. First, we use 
filterNot()
 to filter out banned words. 
filterNot { it in banned }
 will return a 
List<String>
 that contains only those strings that are not in the 
banned
 array. Unlike 
groupBy()
 that returns a map, 
groupingBy()
 returns an object of 
Grouping
 type, that could be used later with one of group-and-fold operations. We use it in 
groupingBy()
 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 
eachCount()
 on the 
Grouping
.
4. We use 
maxBy()
 function to get the first largest element in the map, by 
value
. 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 
LinkedHashSet
 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 

LinkedHashMap
 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 

map
flatMap
count
find
sum
partition
 and much more!