In-place reverse a list in Kotlin
This article explores different ways to in-place reverse a list in Kotlin.
The conversion should be done in-place, i.e., without using any auxiliary space by overwriting the existing elements of the specified list.
1. Using Collections.reverse() function
To in-place reverse the order of the elements in a list, you can use the Collections.reverse() function. It takes the list whose elements are to be reversed.
|
1 2 3 4 5 6 7 8 9 |
import java.util.Collections fun main() { val days: List<String> = listOf("Sunday", "Monday", "Friday") Collections.reverse(days) println(days) // [Friday, Monday, Sunday] } |
2. Using reversed() function
You can also use the native reversed() function to reverse a list, but the conversion won’t be in-place, and it creates a new list.
|
1 2 3 4 5 6 7 |
fun main() { val days: List<String> = listOf("Sunday", "Monday", "Friday") val reversedList = days.reversed(); println(reversedList) // [Friday, Monday, Sunday] } |
If you just need the view of the list in reverse order, you can get one using the asReversed() function.
|
1 2 3 4 5 6 7 |
fun main() { val days: List<String> = listOf("Sunday", "Monday", "Friday") val reversedView = days.asReversed(); println(reversedView) // [Friday, Monday, Sunday] } |
2. Using add() with removeLast() function
Another plausible way to in-place reverse a list is to reorder the elements within the list. We can do this by removing an element from the end of the list and insert it into the very beginning, one at a time, using a for-loop.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val days: MutableList<String> = mutableListOf("Sunday", "Monday", "Friday") for (i in days.indices) { days.add(i, days.removeLast()) } println(days) // [Friday, Monday, Sunday] } |
3. Using Recursion
Finally, you can use recursion to in-place reverse a list. Here’s a recursive solution:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
fun <T> reverseList(list: MutableList<T>?) { // base case: the list is empty, or only one element is left if (list == null || list.size <= 1) { return } // remove the first element val value = list.removeFirst() // recur for remaining items reverseList(list) // insert the top element back after recur for remaining items list.add(value) } fun main() { val days: MutableList<String> = mutableListOf("Sunday", "Monday", "Friday") reverseList(days) println(days) // [Friday, Monday, Sunday] } |
That’s all about in-place reversing a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)