Search code examples
javapalindrome

check if an array is a palindrome or not with just index as a parameter


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.


Solution

  • 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