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 , 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. Kotlin Koans 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 of 10 elements and you want to print . IntArray 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 123456789 array = intArrayOf( , , , , , , , , , ) (index ( until array.size)) { print(array[index]) } val 0 1 2 3 4 5 6 7 8 9 for in 1 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 right? (1 until array.size) IntRange Int 1 9 until ArrayIndexOutOfBoundsException 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. 012346789 if array = intArrayOf( , , , , , , , , , ) (index array.indices - ) { print(array[index]) } val 0 1 2 3 4 5 6 7 8 9 for in 5 returns the range of valid indices for the array. In this case represent of . Making will result in . This is exactly what we need. array.indices array.indices IntRange (0..9) (0..9) - 5 [0, 1, 2, 3, 4, 6, 7, 8, 9] 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 . downTo step array = intArrayOf( , , , , , , , , , ) (index array.size - downTo step ) { print(array[index]) } val 0 1 2 3 4 5 6 7 8 9 for in 1 1 2 The code above with result in . 97531 Remove Vowels from a String It’s problem number on Leetcode. 1119 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 String removeVowels(String S) { StringBuilder sb = new StringBuilder(); (char s: S.toCharArray()) { (s != && s != && s != && s != && s != ) { sb.append(s); } } sb.toString(); } public for if 'a' 'e' 'i' 'o' 'u' return What about Kotlin? More idiomatic way is to use or . filter() filterNot() : String { vowels = setOf( , , , , ) S.filter { it ! vowels } } fun removeVowels (S: ) String val 'a' 'e' 'i' 'o' 'u' return in returns a string containing only those characters from the original string that match the given predicate. filter {predicate: (Char) -> Boolean} But instead of inverting let’s use !in filterNot() : String { vowels = setOf( , , , , ) S.filterNot { it vowels } } fun removeVowels (S: ) String val 'a' 'e' 'i' 'o' 'u' return in 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. nums = [1,2,3,4] [1,3,6,10] Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4]. Input: Output: Explanation: 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 and operations. fold() reduce() Here’s of those functions. But since Kotlin 1.4 there’s even more: and . 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. a good explanation runningFold() runningReduce() runningReduce() . .InlineOnly -> ): List< > /** * 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. * * [operation] function that takes current accumulator value and an element, and calculates the next accumulator value. * * samples.collections.Collections.Aggregates.runningReduce */ @param @sample @SinceKotlin( ) "1.4" @kotlin internal public inline IntArray. fun runningReduce (operation: ( : , ) acc Int Int Int Int Sounds a bit too complex, but it will make sense when you’ll see an example. : IntArray { nums.runningReduce { sum, element -> sum + element }.toIntArray() } fun runningSum (nums: ) IntArray return This is the whole solution to the running sum problem using Kotlin function. 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: runningReduce() sum element sum sum element 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 . There is no , I didn’t miss the line. The thing is that , as we see in the doc, takes the first value as the initial accumulator. [1, 3, 6, 10, 15] sum + element: 1 runningReduce 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"] "ball" Input: Output: 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. String mostCommonWord(String paragraph, String[] banned) { String[] words = paragraph.replaceAll( , ).toLowerCase().split( ); Set<String> bannedWords = new HashSet(); (String word : banned) bannedWords.add(word); Map<String, Integer> wordCount = new HashMap(); (String word : words) { (!bannedWords.contains(word)) wordCount.put(word, wordCount.getOrDefault(word, ) + ); } Collections.max(wordCount.entrySet(), Map.Entry.comparingByValue()).getKey(); } public // 1. Covert string to lower case and split by words. "[^a-zA-Z0-9 ]" " " "\\s+" // 2. Create a set of banned words. for // 3. Create a map of words to their occurrence, excluding the banned words for if 0 1 // 4. Return word with the highest number of occurrences from the map. return And the same 4 steps in Kotlin. : String { words = paragraph.toLowerCase().split( .toRegex()) bannedSet = banned.toHashSet() wordToCount = words.filterNot { it bannedSet }.groupingBy { it }.eachCount() wordToCount.maxBy { it.value }!!.key } fun mostCommonWord (paragraph: , banned: < >) String Array String // 1. Covert string to lower case and split by words. val "\\W+|\\s+" // 2. Create a set of banned words. val // 3. Create a map of words to their occurrence, excluding the banned words val in // 4. Return word with the highest number of occurrences from the map. return Now let’s go through the functions to see what is happening here. 1. We split the string into . The type is inferred. 2. Converting to to make checks in O(1) time 3. In this step, we chain 3 function calls. First, we use to filter out banned words. 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 , e.g. . And we return a key, which is the most common word in the sentence. words: List<String> banned: Array<String> HashSet in filterNot() filterNot { it in banned } List<String> banned groupBy() groupingBy() Grouping groupingBy() eachCount() Grouping maxBy() value Map.Entry<String, Int>? ball = 2 Order of elements When you create a set using or converting array to set using the returned set is and therefore element iteration order is preserved. setOf(“a”, “b”, “c”) arrayOf(“a”, “b”, “c”).toSet() LinkedHashSet 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. LinkedHashMap I have covered just a few of all available collection functions in Kotlin. There’s , , , , , and much more! map flatMap count find sum partition