Home » Java » java – check if an array is a palindrome or not with just index as a parameter-Exceptionshub

java – check if an array is a palindrome or not with just index as a parameter-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
import java.util.Scanner;

public class Palindrome1 {

    public static boolean palindrome(int[] num, int index) {
        //write the logic here

            int length = num.length;
            int end = --length;

            if (length == 0 || length == 1)
                return true;

            if (index >= end)
               return true;

            if(num[index]!=num[end])
                return false;

            return palindrome(num, index+1);
    }


    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int num[] = new int[5];
        for(int i=0; i< 5;i++)
            num[i]=sc.nextInt();
        boolean answer =palindrome(num, 0);
        System.out.println(answer);
    }
}

It is easy if I had an end index value where I could have auto decremented. However with just index how can we solve it? Remember I should not be changing the number of params for the isPalindrome method.
Thanks in advance.

How to&Answers:

Subtract index from end too

int end = --length;

end -= index;

to check the corresponding index from both ends

public static boolean isPalindrome(int[] num, int index) {
    int length = num.length;
    int end = --length;
    end -=index;

    print(num, index, end);

    if (length == 0 || length == 1)
        return true;

    if (index >= end)
        return true;

    if(num[index]!=num[end])
        return false;

    return isPalindrome(num, index+1);
}

private static void print(int num[], int index, int end) {
    for (int i = 0; i < num.length; i++) {
        if(i == index || i == end)
            System.out.print("["+num[i]+"]");
        else
            System.out.print("_,");
    }

    System.out.println();
}

Output

[1]_,_,_,[1]
_,[2]_,[2]_,
_,_,[3]_,_,
true

Answer:

From https://www.geeksforgeeks.org/program-to-check-if-an-array-is-palindrome-or-not/

class GfG { 

    static void palindrome(int arr[], int n) 
    { 
        // Initialise flag to zero. 
        int flag = 0; 

        // Loop till array size n/2. 
        for (int i = 0; i <= n / 2 && n != 0; i++) { 

            // Check if first and last element are different 
            // Then set flag to 1. 
            if (arr[i] != arr[n - i - 1]) { 
                flag = 1; 
                break; 
            } 
        } 

        // If flag is set then print Not Palindrome 
        // else print Palindrome. 
        if (flag == 1) 
            System.out.println("Not Palindrome"); 
        else
            System.out.println("Palindrome"); 
    } 

    // Driver code. 
    public static void main(String[] args) 
    { 
        int arr[] = { 1, 2, 3, 2, 1 }; 
        int n = arr.length; 

        palindrome(arr, n); 
    } 
}