I am new to Kotlin and I am learning the language by solving simple puzzles in IntelliJ, using the tips presented by the IDE. I wrote this piece of code (Finding the most repeated number):
fun main(args: Array<String>) {
val tracer = mutableMapOf<Int,Int>()
var currentMaxCount = 0
val numbers = readLine()!!.split(' ').map(String :: toInt)
for(number in numbers) {
val currentCountOfNum = incrementAndGetCurrentCountOf(number, tracer)
currentMaxCount = if(currentCountOfNum > currentMaxCount) currentCountOfNum else currentMaxCount
}
println(currentMaxCount)
}
fun incrementAndGetCurrentCountOf(num : Int, tracer: MutableMap<Int,Int>) =
if(tracer[num] == null) {
tracer.put(num, 1)
1
} else {
val newCount = tracer[num]!! + 1
tracer.put(num, newCount)
newCount
}
And the IDE suggested that the following code:
var currentMaxCount = 0
for(number in numbers) {
val currentCountOfNum = incrementAndGetCurrentCountOf(number, tracer)
currentMaxCount = if(currentCountOfNum > currentMaxCount) currentCountOfNum else currentMaxCount
}
be changed to this:
val currentMaxCount = numbers
.map { incrementAndGetCurrentCountOf(it, tracer) }
.max()
?: 0
I understand what is happening. But I was wondering if the performance would become O(2n) if I use the IDE's suggestion. It's O(n) in what I came up with. I know it theoretically doesn't make a difference, but I would like know if Kotlin uses any magic to keep the running time at O(n). (Any additional suggestions to further shrink the code are welcome)