Learn-dsa..in 30 days!



























CC-4 : Check if array elements are arranged as a palindrome.

Description:

A palindrome is a word, number or sequence which has same order in backward or forward direction. Given an input integer array arr, check if the array elements are arranged like a palindrome. Required time complexity is O(n).

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4,3,2,1} The array is a Palindrome.
arr={9,-1,-1,9} The array is a Palindrome.
arr={1,3,5,7,9,11,17 } The array is not a Palindrome.
arr={1,3,5,7,5,3,0 } The array is not a Palindrome.

Pseudocode:

The java method should accept following input parameters: arr (int array).
Initialize int variable leftIdx to 0 and int variable rightIdx to arr.length-1.
Initialize a boolean variable isPalindome to false.
Compare the value of array element at leftIdx with value at rightIdx. If they are the same, then the check for palindrome elements has passed for current indexes, so set isPalindome to true. If they are not same, check for palindrome has failed, set isPalindome to false. If check for palindrome fails even once, no further checking is required.
Increment leftIdx by 1 and decrement rightIdx by 1. Again, repeat the check in step above.
Repeat above steps using while loop till leftIdx < rightIdx.
After while loop ends return the value of isPalindome.

Code:

public boolean arrayCheckPalindrome(int[] arr) throws Exception{
	int leftIdx=0;
	int rightIdx=arr.length-1;
	boolean isPalindrome=true;
	while (leftIdx < rightIdx) {
		if (arr[leftIdx]==arr[rightIdx]) {
			leftIdx++;
			rightIdx--;
			continue;
		}else {
			isPalindrome=false;
			break;
		}			
	}		
	if (isPalindrome==true) {
		return true;	
	}else {
		return false;	
	}
}

Click here to download and run code and test cases !