루피도 코딩한다

[Kotlin] Shortening 1 sec in Problem Solving; withIndex() and associate() Functions 본문

Algorithm

[Kotlin] Shortening 1 sec in Problem Solving; withIndex() and associate() Functions

xiaolin219 2024. 2. 16. 01:10

Thanks to Kotlin's functional programming features, we can efficiently solve algorithmic problems compared to using traditional languages. In this post, we'll explore how to transform a list into a map under specific conditions in just one line using withIndex() and associate().

1. Basic Notion

withIndex()

withIndex() is an extension function for collections in Kotlin. It enables iteration over a collection while accessing both index and value. This feature is useful for operations based on index during iteration.

associate()

associate() transforms a collection into a map in Kotlin. It takes a lambda function, defining how to convert each element into a key-value pair. This function is handy for converting collections into maps based on specific criteria.

Comparison with mapIndexed()

While withIndex() and mapIndexed() both provide index access during iteration, withIndex() offers a cleaner syntax and is more efficient for large datasets. On the other hand, mapIndexed() requires explicit index handling, which may introduce performance overhead.

2. Code Using mapIndexed() vs withIndex() and associate()

val list = br.readLine().split(" ").map { it.toInt() }.toIntArray()
val sortedUniqueList = list.toHashSet().sorted().toList()

// This can be change like..
val hashMap = linkedMapOf<Int, Int>()
sortedUniqueList.mapIndexed { idx, value ->
    hashMap[value] = idx
}

// this!
val indexMap = sortedUniqueList.withIndex().associate { (index, value) -> value to index }

3. Performance Considerations

One of the most important thing to consider on PS is the performance.

mapIndexed() operates by executing a lambda for each element and creating a new map, while associate() creates a new map in one go. Therefore, for very large datasets, associate() may be slightly more efficient.

For real, when I submit both code one with the mapIndexed() against the one with the withIndex() and associate(), the latter one shows slightly higher time efficiency.

image-20240216005651225

Comments