Kotlin Program to Reverse a String with Example
You can reverse a string in Kotlin using
val reversed = original.reversed() which returns the reversed string.Examples
Inputhello
Outputolleh
InputKotlin
OutputniltoK
Input
Output
How to Think About It
To reverse a string, think of reading the characters from the end to the start and putting them in a new string. Kotlin provides a simple function
reversed() that does this for you, so you just call it on the original string.Algorithm
1
Get the input string from the user or predefined variable.2
Use the built-in <code>reversed()</code> function to reverse the string.3
Store the reversed string in a new variable.4
Print or return the reversed string.Code
kotlin
fun main() {
val original = "hello"
val reversed = original.reversed()
println(reversed)
}Output
olleh
Dry Run
Let's trace the string "hello" through the code
1
Original string
original = "hello"
2
Reverse string using reversed()
reversed = "hello".reversed() -> "olleh"
3
Print reversed string
Output: olleh
| Index | Character | Reversed Position |
|---|---|---|
| 0 | h | 4 |
| 1 | e | 3 |
| 2 | l | 2 |
| 3 | l | 1 |
| 4 | o | 0 |
Why This Works
Step 1: Using reversed() function
The reversed() function creates a new string by reading the original string from the last character to the first.
Step 2: Storing the result
We store the reversed string in a new variable so we can use or print it later.
Step 3: Printing the reversed string
Finally, we print the reversed string to show the output.
Alternative Approaches
Manual loop reversal
kotlin
fun main() {
val original = "hello"
var reversed = ""
for (i in original.length - 1 downTo 0) {
reversed += original[i]
}
println(reversed)
}This method uses a loop to build the reversed string manually but is less efficient due to string concatenation.
Using StringBuilder reverse()
kotlin
fun main() {
val original = "hello"
val reversed = StringBuilder(original).reverse().toString()
println(reversed)
}This uses StringBuilder's reverse method which is efficient and mutable, good for longer strings.
Complexity: O(n) time, O(n) space
Time Complexity
The reversal reads each character once, so it takes linear time proportional to the string length.
Space Complexity
A new string is created to hold the reversed characters, so space is also linear in the string length.
Which Approach is Fastest?
Using reversed() or StringBuilder.reverse() is faster and more efficient than manual concatenation loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| reversed() | O(n) | O(n) | Simple and clean code |
| StringBuilder.reverse() | O(n) | O(n) | Efficient for large strings |
| Manual loop with concatenation | O(n²) | O(n) | Educational but inefficient |
Use Kotlin's built-in
reversed() function for the simplest and cleanest string reversal.Beginners often try to reverse strings by concatenating characters in a loop without using StringBuilder, which is inefficient.