Kotlin Program to Check Palindrome String
input == input.reversed().Examples
How to Think About It
==.Algorithm
Code
fun main() {
print("Enter a string: ")
val input = readLine() ?: ""
if (input == input.reversed()) {
println("$input is a palindrome")
} else {
println("$input is not a palindrome")
}
}Dry Run
Let's trace the input 'madam' through the code
Read input
input = 'madam'
Reverse input
input.reversed() = 'madam'
Compare strings
'madam' == 'madam' is true
Print result
Print 'madam is a palindrome'
| Step | Input | Reversed | Comparison Result |
|---|---|---|---|
| 1 | madam | madam | true |
Why This Works
Step 1: Reading input
We get the string from the user using readLine() which reads text from the keyboard.
Step 2: Reversing the string
Using input.reversed() creates a new string with characters in reverse order.
Step 3: Comparing strings
We use == to check if the original string and reversed string are exactly the same.
Step 4: Output result
If they match, we print that the string is a palindrome; otherwise, we say it is not.
Alternative Approaches
fun main() {
print("Enter a string: ")
val input = readLine() ?: ""
var isPalindrome = true
for (i in 0 until input.length / 2) {
if (input[i] != input[input.length - 1 - i]) {
isPalindrome = false
break
}
}
if (isPalindrome) {
println("$input is a palindrome")
} else {
println("$input is not a palindrome")
}
}fun String.isPalindrome(): Boolean = this == this.reversed() fun main() { print("Enter a string: ") val input = readLine() ?: "" if (input.isPalindrome()) { println("$input is a palindrome") } else { println("$input is not a palindrome") } }
Complexity: O(n) time, O(n) space
Time Complexity
Reversing the string takes O(n) time where n is the string length, and comparing two strings also takes O(n). Overall, it is O(n).
Space Complexity
The reversed string creates a new string of length n, so space complexity is O(n).
Which Approach is Fastest?
Manual character comparison can be faster in practice because it stops early on mismatch and uses O(1) extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using reversed() | O(n) | O(n) | Simple and readable code |
| Manual character comparison | O(n) best case less | O(1) | Large strings with early mismatch |
| Extension function | O(n) | O(n) | Reusable and clean code |
input == input.reversed() for a quick palindrome check in Kotlin.