Find the Longest Palindrome in an Array using Python

longest palindrome in array

Longest Palindrome in an Array

Here, in this page we will discuss the program to find the longest palindrome in an array in python programming language, we will discuss two different methods to find the longest palindromic element in the given array.

 

Here in this page we will discuss the following methods to find the longest palindromic number.

  • Method 1 : Using Naive Approach
  • Method 2 : Using Sorting

Method 1 :

  • Create a function ispalindrome(int n), it will return 1 if the passing number is palindrome otherwise return 0.
  • Inside the main function, create a variable say res = -1, that hold the maximum palindrome number.
  • Run a loop from [0, n),  and check if(ispalindrome(arr[i]) && res<arr[i]), then set res = arr[i].
  • Print the value of res.
Longest Palindrome in an array

Method 1 : Code in Python

Run
# Function to check if n is palindrome
def isPalindrome(n):

   divisor = 1
   while (int(n / divisor) >= 10):
      divisor *= 10

   while (n != 0):
      leading = int(n / divisor)
      trailing = n % 10
  
      if (leading != trailing):
        return False

      n = int((n % divisor) / 10)

      divisor = int(divisor / 100)
   return True

# Function to find the largest palindromic element
def largestPalindrome(arr, n):
   currentMax = -1

   for i in range(0, n, 1):
      if (arr[i] > currentMax and isPalindrome(arr[i])):
         currentMax = arr[i]

   return currentMax

# Driver Code

arr = [1, 232, 5545455, 909090, 161]
n = len(arr)

# print required answer
print(largestPalindrome(arr, n))

Output

5545455

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Method 2 :

In this method we first sort the array and then start traversing the array from end, and return the element that satisfy the condition, that it is palindrome.

  • Sort the array using inbuilt sort() function.
  • Start traversing from end of the array,
  • Print the element if it is palindrome.
  • If no element found then print -1.

Method 2 : Code in Python

Run
# Function to check if n is palindrome
def isPalindrome(n):

   divisor = 1
   while (int(n / divisor) >= 10):
      divisor *= 10

   while (n != 0):
      leading = int(n / divisor)
      trailing = n % 10
  
      if (leading != trailing):
        return False

      n = int((n % divisor) / 10)

      divisor = int(divisor / 100)
   return True

# Function to find the largest palindromic element
def largestPalindrome(A, n) :
    # Sort the array
    A.sort()

    for i in range(n - 1, -1, -1) :
        # If number is palindrome
        if (isPalindrome(A[i])) :
            return A[i]    

    # If no palindromic number found
    return -1

# Driver Code 
arr = [1, 232, 5545455, 909090, 161]
n = len(arr) 
# print required answer 
print(largestPalindrome(arr, n))

Output

5545455

21 comments on “Find the Longest Palindrome in an Array using Python”


  • Vidyashree

    arr = [1, 232, 5545455, 909090, 161]
    len_array=[]
    for i in range(len(arr)):
    len_array.append(0)
    for i in arr:
    temp=i
    rem=0
    rev=0
    count=0
    while(i!=0):
    rem=i%10
    rev=rev*10+rem
    i=i//10
    count+=1
    if rev==temp:
    len_array.insert(count,temp)

    print(len_array[len(len_array)-1])


  • CS3139_Neha

    def is_pallindrome(Arr):
    l=[]
    for i in range(len(Arr)):
    a=Arr[i]
    if a==a[::-1]:
    l.append(int(a))
    maxi=-1
    for i in range(0,len(l)):
    if int(l[i])>maxi:
    maxi=l[i]
    print(maxi)

    Arr=list(input().split())
    is_pallindrome(Arr)


  • RADHIKA

    #palindrome number longest
    arr=list(map(int,input().split()))
    z=1
    for i in arr:
    if str(i)==str(i)[::-1]:
    if len(str(i))>z:
    z=i
    print(z)


  • Ruturaj

    my approach
    arr=[101,202,230,303,2002,3250]
    max=arr[0]
    for i in range(len(arr)):
    reverse = int(str(arr[i])[::-1])
    if arr[i] == reverse and reverse>max:
    max=arr[i]

    print(max)


  • Sanjeet

    //Try this in C: Longest palindrome in array
    #include
    int main()
    {
    int arr[100],n,i,j,l_pallindrome=0;
    printf(“Enter the size of array: “);
    scanf(“%d”,&n);
    for(i=0;i<n;i++)
    {
    scanf("%d",&arr[i]);
    }
    for(i=0;i0)
    {
    rem=temp%10;
    rev=rev*10+rem;
    temp=temp/10;
    }
    if(arr[i]==rev)
    {
    if(rev>l_pallindrome)
    {
    l_pallindrome=rev;
    }
    }
    }
    printf(“The longest palindrome in array : %d”,l_pallindrome);
    return 0;
    }


  • Bibhudutta

    n=int(input())
    arr=list()
    arr1=list()
    for i in range(0,n):
    arr.append(int(input()))

    for i in arr:
    temp=i
    rev=0
    while(temp>0):
    rem=temp%10
    rev=rev*10+rem
    temp=temp//10
    if(i==rev):
    arr1.append(rev)

    print(‘maximum element is -‘,max(arr1))


  • Mayuresh

    arr = list(map(int,input().split())

    a = []

    flag = True

    for i in arr:
    if(str(i) == str(i)[::-1]):
    a.append(i)
    flag = False
    if(flag):
    print(“no palindromic number in array”)
    else:
    print(max(a))


  • Nikita

    def is_palindrome(ele):
    temp = ele
    reverse = 0
    while temp > 0:
    rem = temp % 10
    reverse = reverse * 10 + rem
    temp = temp // 10
    if reverse == ele:
    return digits(ele)
    else:
    return 0

    def digits(ele):
    n = ele
    count = 0
    while n > 0:
    rem = n % 10
    count += 1
    n = n // 10
    return count

    arr = [1210, 11211, 1112111, 141, 11411]
    list = []
    for i in range(len(arr)):
    list.append(is_palindrome(arr[i]))

    def largest(list):
    largest_ele = list[0]
    for i in range(len(list)):
    if largest_ele < list[i]:
    largest_ele = list[i]
    for i in list:
    if largest_ele == list[i]:
    return print(f"{arr[i]} is the longest palindrome with {largest_ele} digits")
    largest(list)


  • Tirtham

    s=int(input())

    lst=[]
    arr=[]
    a=0
    for i in range(0,s,1):
    n=int(input())
    lst.append(n)
    for j in lst:
    if str(j)== str(j) [::-1]:
    arr.append(j)
    arr.sort()
    l=len(arr)
    print(arr[l-1])


  • Arun

    #A number is 526625 .If you read number “526625” from reverse order,
    # it is same as “526625”.
    from array import *
    a= int(input(“enter the number of input :”))
    b=array(“i”,[])
    for x in range(a):
    b1=int(input((“Enter a value :”)))
    b.append(b1)
    m=[]
    for x in range(a):
    c1=str(b[x])
    if c1 == c1[::-1]:
    m.append(c1)
    print(max(m))


  • Shaik

    n=int(input())
    l=[]
    for i in range(n):
    l.append(int(input()))
    l.sort(reverse=True)
    for x in l:
    if str(x)==str(x)[::-1]:
    print(‘longest palindrome’,x)
    break
    else:
    print(‘no’)


  • Pradeep

    //Longest Palindrome in an Array in C language

    #include
    int palindrome(int);
    void main()
    {

    int i, n,count=0,s,c=0;
    printf(“Enter the size of array:”);
    scanf(“%d”,&n);
    int a[n];
    for(i=0;i<n;i++)
    {
    printf("element – %d : ",i);
    scanf("%d",&a[i]);
    }
    int p[20];
    int j;
    for(i=0,j=0;i<n;i++)
    {
    int result=palindrome(a[i]);
    if(result==1)
    {
    p[j++]=a[i];
    c++;
    }
    }
    for(j=0;j<c;j++)
    {
    printf("palindrome array is =%d\n",p[j]);
    }
    int small=p[0];
    for(j=1;j<c;j++)
    {
    if(small0)
    {
    int r=temp%10;
    temp=temp/10;
    sum=sum*10+r;
    }
    if(sum==p)
    {
    return 1;
    }
    else
    {
    return 0;
    }
    }