Kotlin Program to Check Palindrome String
val isPalindrome = input == input.reversed().Examples
How to Think About It
==.Algorithm
Code
fun main() {
print("Enter a string: ")
val input = readLine() ?: ""
val isPalindrome = input == input.reversed()
if (isPalindrome) {
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
Output: '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 to check if it is a palindrome.
Step 2: Reversing the string
Using input.reversed() creates a new string with characters in reverse order.
Step 3: Comparing strings
If the original string and reversed string are exactly the same, the string is a palindrome.
Step 4: Output result
Print a message telling the user if the string is a palindrome or not.
Alternative Approaches
fun main() {
print("Enter a string: ")
val input = readLine() ?: ""
var isPalindrome = true
val length = input.length
for (i in 0 until length / 2) {
if (input[i] != input[length - 1 - i]) {
isPalindrome = false
break
}
}
if (isPalindrome) {
println("$input is a palindrome")
} else {
println("$input is not a palindrome")
}
}fun isPalindrome(s: String): Boolean {
if (s.length <= 1) return true
if (s.first() != s.last()) return false
return isPalindrome(s.substring(1, s.length - 1))
}
fun main() {
print("Enter a string: ")
val input = readLine() ?: ""
if (isPalindrome(input)) {
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 strings also takes O(n). Overall, the time complexity is O(n).
Space Complexity
The reversed string creates a new string of length n, so space complexity is O(n). The manual comparison method uses O(1) extra space.
Which Approach is Fastest?
Manual character comparison is faster and uses less memory than reversing the string, especially for large inputs.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using reversed() | O(n) | O(n) | Simplicity and readability |
| Manual character comparison | O(n) | O(1) | Memory efficiency and large inputs |
| Recursion | O(n) | O(n) | Elegant code but less efficient for large strings |
input == input.reversed() for a quick and readable palindrome check in Kotlin.