I solved this easy LC problem in less than 5 minutes. Solution is very easy and straightforward. I provided two solutions: One that uses the map operator and another using the good ‘ole for loop.

class Solution {
fun calculateTime(keyboard: String, word: String): Int {
var prevIndex = 0
return word.map { w ->
val index = keyboard.indexOf(w)
val distance = if(index == prevIndex) 0 else Math.abs(prevIndex - index)
prevIndex = index
distance
}.sum()
}
}

Runtime: 192 ms, faster than 20.00% of Kotlin online submissions for Single-Row Keyboard.
Memory Usage: 35.4 MB, less than 100.00% of Kotlin online submissions for Single-Row Keyboard.

class Solution {
fun calculateTime(keyboard: String, word: String): Int {
var prevIndex = 0
var sum = 0
for(w in word){
val index = keyboard.indexOf(w)
val distance = if(index == prevIndex) 0 else Math.abs(prevIndex - index)
prevIndex = index
sum += distance
}

return sum
}
}

Runtime: 168 ms, faster than 80.00% of Kotlin online submissions for Single-Row Keyboard.
Memory Usage: 35.5 MB, less than 100.00% of Kotlin online submissions for Single-Row Keyboard.


Why is map operator slower than for-loop? I also seems to notice that this is always the case. Would any have a good explanation about this?