How to Use Kotlin to Solve Coding Problems

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







(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.

#kotlin #programming #android #java #mobile-apps

What is GEEK

Buddha Community

How to Use Kotlin to Solve Coding Problems
Vincent Lab

Vincent Lab


How to do Problem Solving as a Developer

In this video, I will be talking about problem-solving as a developer.

#problem solving skills #problem solving how to #problem solving strategies #problem solving #developer

Tyrique  Littel

Tyrique Littel


Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer


We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:


The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:



import io


import tokenize



code = b"color = input('Enter your favourite color: ')"



for token in tokenize.tokenize(io.BytesIO(code).readline):





TokenInfo(type=62 (ENCODING),  string='utf-8')


TokenInfo(type=1  (NAME),      string='color')


TokenInfo(type=54 (OP),        string='=')


TokenInfo(type=1  (NAME),      string='input')


TokenInfo(type=54 (OP),        string='(')


TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")


TokenInfo(type=54 (OP),        string=')')


TokenInfo(type=4  (NEWLINE),   string='')


TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Juned Ghanchi


Kotlin App Development Company in India, Hire Kotlin Developers

We are a prime Kotlin app developer in India. We build and provide the best personalized Android apps, migration services, ongoing maintenance, and management.

We have the most efficient Kotlin developers that build ultramodern, interactive, and secure mobile apps. The technologies we use to create the most advanced Kotlin apps are AR/VR, AI/ML, IoT, etc.

Hire Kotlin app developers in India. Meet us, and we will help you meet all of your technology requirements.

#kotlin app development company india #hire kotlin developers india #kotlin app development company #hire kotlin developers #kotlin development agency #kotlin app programmers

Vincent Lab

Vincent Lab


How to Ask a Good Question on the Internet as a Programmer

In this video, I will be talking about how to ask for help as a developer.

#problem solving skills #problem solving how to #coding interviews #problem solving #how to ask a good question

Samanta  Moore

Samanta Moore


Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review