Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Reverse

Reversing a list is similar to reversing a string, after all string is list of characters only. So we have two approaches - one, in-place using swaps and two, using a new list. In-place is more efficient than new list approach because it does not require extra space (new list).

Following is the implementation of in-place approach :

 fun <T> List<T>.reversed(): List<T> {
    val list = toMutableList()
    for (i in 0 until (size / 2)) {
        list[i] = list[lastIndex - i].apply {
            list[lastIndex - i] = list[i]
        }
    }
    return list
}