Kotlin Program to Reverse List with Example and Explanation
reversed() function like val reversedList = originalList.reversed() which returns a new list with elements in reverse order.Examples
How to Think About It
reversed() that does this for you by creating a new list with elements in reverse order.Algorithm
Code
fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val reversedList = originalList.reversed()
println(reversedList)
}Dry Run
Let's trace the list [1, 2, 3, 4, 5] through the code
Original List
originalList = [1, 2, 3, 4, 5]
Call reversed()
reversedList = originalList.reversed()
Resulting List
reversedList = [5, 4, 3, 2, 1]
Print Output
Output: [5, 4, 3, 2, 1]
| Step | List State |
|---|---|
| 1 | [1, 2, 3, 4, 5] |
| 2 | [5, 4, 3, 2, 1] |
Why This Works
Step 1: Using reversed() Function
The reversed() function creates a new list with elements in the opposite order of the original list.
Step 2: Immutable Original List
The original list remains unchanged because reversed() returns a new list instead of modifying the original.
Step 3: Printing the Result
Printing the reversed list shows the elements from last to first, confirming the reversal.
Alternative Approaches
fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val reversedList = originalList.toTypedArray().reversedArray().toList()
println(reversedList)
}fun main() {
val originalList = listOf(1, 2, 3, 4, 5)
val reversedList = mutableListOf<Int>()
for (i in originalList.size - 1 downTo 0) {
reversedList.add(originalList[i])
}
println(reversedList)
}Complexity: O(n) time, O(n) space
Time Complexity
The reversed() function iterates over all elements once, so it takes linear time proportional to the list size.
Space Complexity
It creates a new list to hold the reversed elements, so it uses extra space proportional to the list size.
Which Approach is Fastest?
Using reversed() is the fastest and most readable. Manual loops are slower and more error-prone. Array conversion adds overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| reversed() | O(n) | O(n) | Simple and readable reversal |
| reversedArray() with conversion | O(n) | O(n) | When working with arrays |
| Manual loop | O(n) | O(n) | Learning reversal logic explicitly |
reversed() for a simple and readable way to reverse lists in Kotlin.