Skip to main content

How to check if an array is palindrome in Kotlin

How to check if an array is palindrome in Kotlin.

Here's a step-by-step tutorial on how to check if an array is a palindrome in Kotlin:

  1. Start by creating a function named isPalindrome that takes an array as input and returns a Boolean value indicating whether the array is a palindrome or not.

  2. Inside the isPalindrome function, initialize two variables start and end with the values 0 and array.size - 1 respectively. These variables will be used to iterate through the array from both ends.

  3. Create a while loop that runs as long as start is less than or equal to end. This loop will compare the corresponding elements from both ends of the array.

  4. Inside the loop, compare array[start] with array[end]. If they are not equal, return false as it means the array is not a palindrome.

  5. After comparing the elements, increment start by 1 and decrement end by 1 to move towards the center of the array.

  6. If the loop completes without returning false, it means all the corresponding elements from both ends of the array were equal. In this case, return true to indicate that the array is a palindrome.

  7. To test the isPalindrome function, create an array with some values and call the function, passing the array as an argument. Print the result to the console.

Here's an example implementation of the isPalindrome function:

fun isPalindrome(array: IntArray): Boolean {
var start = 0
var end = array.size - 1

while (start <= end) {
if (array[start] != array[end]) {
return false
}
start++
end--
}
return true
}

fun main() {
val array1 = intArrayOf(1, 2, 3, 2, 1)
val array2 = intArrayOf(1, 2, 3, 4, 5)

println(isPalindrome(array1)) // Output: true
println(isPalindrome(array2)) // Output: false
}

In this example, array1 is a palindrome because the elements are the same when read from left to right or right to left. On the other hand, array2 is not a palindrome because the elements are different when read in reverse.

Feel free to modify the code and test it with different arrays to check if they are palindromes.