Given an array of non-negative integers arr[]. The task is to find the largest number in the array which is palindrome. If no such number exits then print -1.
Examples:
Input: arr[] = {1, 232, 54545, 999991};
Output: 54545Input: arr[] = {1, 2, 3, 4, 5, 50};
Output: 5
Method 1:
- Sort the array in ascending order.
- Start traversing the array from the end.
- The first number which is a palindrome is the required answer.
- If no palindromic number is found then print -1
Below is the implementation of the above approach:
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std;
// Function to check if n is palindrome bool isPalindrome( int n)
{ // Find the appropriate divisor
// to extract the leading digit
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100;
}
return true ;
} // Function to find the largest palindromic number int largestPalindrome( int A[], int n)
{ // Sort the array
sort(A, A + n);
for ( int i = n - 1; i >= 0; --i) {
// If number is palindrome
if (isPalindrome(A[i]))
return A[i];
}
// If no palindromic number found
return -1;
} // Driver program int main()
{ int A[] = { 1, 232, 54545, 999991 };
int n = sizeof (A) / sizeof (A[0]);
// print required answer
cout << largestPalindrome(A, n);
return 0;
} |
// Java implementation of above approach import java.util.*;
class GFG
{ // Function to check if n is palindrome
static boolean isPalindrome( int n)
{
// Find the appropriate divisor
// to extract the leading digit
int divisor = 1 ;
while (n / divisor >= 10 )
divisor *= 10 ;
while (n != 0 ) {
int leading = n / divisor;
int trailing = n % 10 ;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10 ;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100 ;
}
return true ;
}
// Function to find the largest palindromic number
static int largestPalindrome( int []A, int n)
{
// Sort the array
Arrays.sort(A);
for ( int i = n - 1 ; i >= 0 ; --i) {
// If number is palindrome
if (isPalindrome(A[i]))
return A[i];
}
// If no palindromic number found
return - 1 ;
}
// Driver program
public static void main(String []args)
{
int []A = { 1 , 232 , 54545 , 999991 };
int n = A.length;
// print required answer
System.out.println(largestPalindrome(A, n));
}
} // This code is contributed // by ihritik |
# Python3 implementation of above approach # Function to check if n is palindrome def isPalindrome(n) :
# Find the appropriate divisor
# to extract the leading digit
divisor = 1
while (n / divisor > = 10 ) :
divisor * = 10
while (n ! = 0 ) :
leading = n / / divisor
trailing = n % 10
# If first and last digits are
# not same then return false
if (leading ! = trailing) :
return False
# Removing the leading and trailing
# digits from the number
n = (n % divisor) / / 10
# Reducing divisor by a factor
# of 2 as 2 digits are dropped
divisor = divisor / / 100
return True
# Function to find the largest # palindromic number 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 if __name__ = = "__main__" :
A = [ 1 , 232 , 54545 , 999991 ]
n = len (A)
# print required answer
print (largestPalindrome(A, n))
# This code is contributed by Ryuga |
// C# implementation of above approach using System;
class GFG
{ // Function to check if n is palindrome
static bool isPalindrome( int n)
{
// Find the appropriate divisor
// to extract the leading digit
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100;
}
return true ;
}
// Function to find the largest palindromic number
static int largestPalindrome( int []A, int n)
{
// Sort the array
Array.Sort(A);
for ( int i = n - 1; i >= 0; --i) {
// If number is palindrome
if (isPalindrome(A[i]))
return A[i];
}
// If no palindromic number found
return -1;
}
// Driver program
public static void Main()
{
int []A = { 1, 232, 54545, 999991 };
int n = A.Length;
// print required answer
Console.WriteLine(largestPalindrome(A, n));
}
} // This code is contributed // by ihritik |
<script> //Javascript implementation of above approach //function for sorting function sort(a, n) {
var i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
} // Function to check if n is palindrome function isPalindrome(n)
{ // Find the appropriate divisor
// to extract the leading digit
var divisor = 1;
while (parseInt(n / divisor) >= 10)
divisor *= 10;
while (n != 0) {
var leading = parseInt(n / divisor);
var trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = parseInt((n % divisor) / 10);
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = parseInt(divisor / 100);
}
return true ;
} // Function to find the largest palindromic number function largestPalindrome( A, n)
{ // Sort the array
sort(A,A.length);
for ( var i = n - 1; i >= 0; --i) {
// If number is palindrome
if (isPalindrome(A[i]))
return A[i];
}
// If no palindromic number found
return -1;
} var A = [ 1, 232, 54545, 999991 ];
var n = A.length;
// print required answer
document.write(largestPalindrome(A, n));
//This code is contributed by SoumikMondal </script> |
<?php // PHP implementation of above approach // Function to check if n is palindrome function isPalindrome( $n )
{ // Find the appropriate divisor
// to extract the leading digit
$divisor = 1;
while ((int)( $n / $divisor ) >= 10)
$divisor *= 10;
while ( $n != 0)
{
$leading = (int)( $n / $divisor );
$trailing = $n % 10;
// If first and last digits are
// not same then return false
if ( $leading != $trailing )
return false;
// Removing the leading and trailing
// digits from the number
$n = (int)(( $n % $divisor ) / 10);
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
$divisor = (int)( $divisor / 100);
}
return true;
} // Function to find the largest // palindromic number function largestPalindrome( $A , $n )
{ // Sort the array
sort( $A );
for ( $i = $n - 1; $i >= 0; -- $i )
{
// If number is palindrome
if (isPalindrome( $A [ $i ]))
return $A [ $i ];
}
// If no palindromic number found
return -1;
} // Driver Code $A = array (1, 232, 54545, 999991);
$n = sizeof( $A );
// print required answer echo largestPalindrome( $A , $n );
// This code is contributed // by Akanksha Rai ?> |
54545
Time complexity : O(nlogn)
Auxiliary space : O(1)
Method 2:
- Set a variable currentMax = -1 and start traversing the array.
- If current element arr[i] > currentMax and arr[i] is a palindrome.
- Then set currentMax = arr[i].
- Print currentMax in the end.
Below is the implementation of the above approach:
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std;
// Function to check if n is palindrome bool isPalindrome( int n)
{ // Find the appropriate divisor
// to extract the leading digit
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100;
}
return true ;
} // Function to find the largest palindromic number int largestPalindrome( int A[], int n)
{ int currentMax = -1;
for ( int i = 0; i < n; i++) {
// If a palindrome larger than the currentMax is found
if (A[i] > currentMax && isPalindrome(A[i]))
currentMax = A[i];
}
// Return the largest palindromic number from the array
return currentMax;
} // Driver program int main()
{ int A[] = { 1, 232, 54545, 999991 };
int n = sizeof (A) / sizeof (A[0]);
// print required answer
cout << largestPalindrome(A, n);
return 0;
} |
// Java implementation of above approach import java.util.*;
class GFG
{ // Function to check if n is palindrome
static boolean isPalindrome( int n)
{
// Find the appropriate divisor
// to extract the leading digit
int divisor = 1 ;
while (n / divisor >= 10 )
divisor *= 10 ;
while (n != 0 ) {
int leading = n / divisor;
int trailing = n % 10 ;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10 ;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100 ;
}
return true ;
}
// Function to find the largest palindromic number
static int largestPalindrome( int []A, int n)
{
int currentMax = - 1 ;
for ( int i = 0 ; i < n; i++) {
// If a palindrome larger than the currentMax is found
if (A[i] > currentMax && isPalindrome(A[i]))
currentMax = A[i];
}
// Return the largest palindromic number from the array
return currentMax;
}
// Driver program
public static void main(String []args)
{
int []A = { 1 , 232 , 54545 , 999991 };
int n = A.length;
// print required answer
System.out.println(largestPalindrome(A, n));
}
} // This code is contributed // by ihritik |
# Python 3 implementation of above approach # Function to check if n is palindrome def isPalindrome(n):
# Find the appropriate divisor
# to extract the leading digit
divisor = 1
while ( int (n / divisor) > = 10 ):
divisor * = 10
while (n ! = 0 ):
leading = int (n / divisor)
trailing = n % 10
# If first and last digits are
# not same then return false
if (leading ! = trailing):
return False
# Removing the leading and trailing
# digits from the number
n = int ((n % divisor) / 10 )
# Reducing divisor by a factor
# of 2 as 2 digits are dropped
divisor = int (divisor / 100 )
return True
# Function to find the largest # palindromic number def largestPalindrome(A, n):
currentMax = - 1
for i in range ( 0 , n, 1 ):
# If a palindrome larger than
# the currentMax is found
if (A[i] > currentMax and isPalindrome(A[i])):
currentMax = A[i]
# Return the largest palindromic
# number from the array
return currentMax
# Driver Code if __name__ = = '__main__' :
A = [ 1 , 232 , 54545 , 999991 ]
n = len (A)
# print required answer
print (largestPalindrome(A, n))
# This code is contributed by # Surendra_Gangwar |
// C# implementation of above approach using System;
class GFG
{ // Function to check if n is palindrome
static bool isPalindrome( int n)
{
// Find the appropriate divisor
// to extract the leading digit
int divisor = 1;
while (n / divisor >= 10)
divisor *= 10;
while (n != 0) {
int leading = n / divisor;
int trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = (n % divisor) / 10;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = divisor / 100;
}
return true ;
}
// Function to find the largest palindromic number
static int largestPalindrome( int []A, int n)
{
int currentMax = -1;
for ( int i = 0; i < n; i++) {
// If a palindrome larger than the currentMax is found
if (A[i] > currentMax && isPalindrome(A[i]))
currentMax = A[i];
}
// Return the largest palindromic number from the array
return currentMax;
}
// Driver program
public static void Main()
{
int []A = { 1, 232, 54545, 999991 };
int n = A.Length;
// print required answer
Console.WriteLine(largestPalindrome(A, n));
}
} // This code is contributed // by ihritik |
<script> // Javascript implementation of above approach // Function to check if n is palindrome function isPalindrome(n)
{ // Find the appropriate divisor
// to extract the leading digit
var divisor = 1;
while (parseInt(n / divisor) >= 10)
divisor *= 10;
while (n != 0)
{
var leading = parseInt(n / divisor);
var trailing = n % 10;
// If first and last digits are
// not same then return false
if (leading != trailing)
return false ;
// Removing the leading and trailing
// digits from the number
n = parseInt((n % divisor) / 10);
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
divisor = parseInt(divisor / 100);
}
return true ;
} // Function to find the largest palindromic number function largestPalindrome(A, n)
{ var currentMax = -1;
for ( var i = 0; i < n; i++)
{
// If a palindrome larger than the
// currentMax is found
if (A[i] > currentMax && isPalindrome(A[i]))
currentMax = A[i];
}
// Return the largest palindromic
// number from the array
return currentMax;
} // Driver code var A = [ 1, 232, 54545, 999991 ];
var n = A.length;
// Print required answer document.write( largestPalindrome(A, n)); // This code is contributed by rrrtnx </script> |
<?php // PHP implementation of above approach // Function to check if n is palindrome function isPalindrome( $n )
{ // Find the appropriate divisor
// to extract the leading digit
$divisor = 1;
while ((int)( $n / $divisor ) >= 10)
$divisor *= 10;
while ( $n != 0)
{
$leading = (int)( $n / $divisor );
$trailing = $n % 10;
// If first and last digits are
// not same then return false
if ( $leading != $trailing )
return false;
// Removing the leading and trailing
// digits from the number
$n = ( $n % $divisor ) / 10;
// Reducing divisor by a factor
// of 2 as 2 digits are dropped
$divisor = $divisor / 100;
}
return true;
} // Function to find the largest // palindromic number function largestPalindrome( $A , $n )
{ $currentMax = -1;
for ( $i = 0; $i < $n ; $i ++)
{
// If a palindrome larger than
// the currentMax is found
if ( $A [ $i ] > $currentMax &&
isPalindrome( $A [ $i ]))
$currentMax = $A [ $i ];
}
// Return the largest palindromic
// number from the array
return $currentMax ;
} // Driver Code $A = array (1, 232, 54545, 999991);
$n = sizeof( $A );
// print required answer echo (largestPalindrome( $A , $n ));
// This code is contributed // by Mukul Singh ?> |
54545
Time complexity : O(n)
Auxiliary space : O(1)
Another Approach in Python using Reverse Slicing –
In this approach we will see how using the reverse slicing and comparing the element with the original element we can identify the largest palindromic number in an array.
#include <algorithm> #include <iostream> #include <string> using namespace std;
// Function to find the largest palindrome in an array long int largest_palindrome( long int arr[], int n)
{ // Initializing it to -1
// So that if there is no palindromic number
// it returns -1
long int pal = -1;
for ( int i = 0; i < n; i++) {
// Converting to string and comparing
// the reverse each time with the
// original one
string str = to_string(arr[i]);
string rev_str = str;
reverse(rev_str.begin(), rev_str.end());
if (str == rev_str) {
// Comparing if i is greater
// than pal then update the value
// of pal
if (arr[i] > pal) {
pal = arr[i];
}
}
}
return pal;
} // Driver Code int main()
{ long int arr[]
= { 1, 232, 54545, 999991, 8813200023188 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << largest_palindrome(arr, n) << endl;
return 0;
} |
public class Main {
// Function to find the largest palindrome in an array
public static long largest_palindrome( long [] arr)
{
// Initializing it to -1
// So that if there is no palindromic number
// it returns -1
long pal = - 1 ;
for ( long i : arr) {
// Converting to string and comparing
// the reverse each time with the
// original one
if (String.valueOf(i).equals(
new StringBuilder(String.valueOf(i))
.reverse()
.toString())) {
// Comparing if i is greater
// than pal then update the value
// of pal
if (i > pal) {
pal = i;
}
}
}
return pal;
}
// Driver Code
public static void main(String[] args)
{
long [] arr
= { 1 , 232 , 54545 , 999991 , 8813200023188L };
System.out.println(largest_palindrome(arr));
}
} // This code is contributed by shivamsharma215 |
def largest_palindrome(arr):
# Initializing it to -1
# So that if there is no palindromic number
# it returns -1
pal = - 1
for i in arr:
# Converting to string and comparing
# the reverse each time with the
# original one
if str (i) = = str (i)[:: - 1 ]:
# Comparing if i is greater
# than pal then update the value
# of pal
if i > pal:
pal = i
else :
pass
return pal
# Driver Code arr = [ 1 , 232 , 54545 , 999991 , 8813200023188 ]
print (largest_palindrome(arr))
|
using System;
using System.Linq;
public class MainClass {
// Function to find the largest palindrome in an array
public static long largest_palindrome( long [] arr)
{
// Initializing it to -1
// So that if there is no palindromic number
// it returns -1
long pal = -1;
foreach ( long i in arr)
{
// Converting to string and comparing
// the reverse each time with the
// original one
if (i.ToString()
== new string (
i.ToString().Reverse().ToArray())) {
// Comparing if i is greater
// than pal then update the value
// of pal
if (i > pal) {
pal = i;
}
}
}
return pal;
}
// Driver Code
public static void Main( string [] args)
{
long [] arr
= { 1, 232, 54545, 999991, 8813200023188L };
Console.WriteLine(largest_palindrome(arr));
}
} |
function largest_palindrome(arr){
let pal = -1;
let n = arr.length;
for (let i = 0;i<n;i++){
let txt = arr[i].toString();
let rev_txt = arr[i].toString().split( "" ).reverse().join( "" )
if (txt == rev_txt){
if (arr[i] > pal){
pal = arr[i];
}
else {
;
}
}
}
return pal;
} arr = [1, 232, 54545, 999991,8813200023188]; console.log(largest_palindrome(arr)); |
8813200023188
Time Complexity – O(n), n is the size of the arr
Auxiliary Space – O(1), No extra space is being used apart from a single variable
Approach#4:using optimized approach
Algorithm
1. Initialize the largest_palindrome_number variable to 0.
2. Iterate through the array.
3. For each element, check if it is a palindrome.
4. If it is a palindrome and greater than the largest_palindrome_number, set largest_palindrome_number to the current element.
5. Iterate through the remaining elements in the array but only check the elements that have more digits than the largest_palindrome_number.
6. Return the largest_palindrome_number.
#include <iostream> #include <string> #include<bits/stdc++.h> // Function to check if a given integer is a palindrome. bool isPalindrome( int n)
{ // Convert the integer to a string.
std::string str = std::to_string(n);
// Create a reversed version of the string.
std::string reversedStr = str;
std::reverse(reversedStr.begin(), reversedStr.end());
// Check if the original string is equal to the reversed
// string.
return str == reversedStr;
} // Function to find the largest palindrome in an array of // integers. int largestPalindromeOptimized( int arr[], int size)
{ int largestPalindromeNumber = 0;
// Iterate through the array.
for ( int i = 0; i < size; i++) {
// Check if the current number is a palindrome and
// greater than the current largest palindrome.
if (isPalindrome(arr[i])
&& arr[i] > largestPalindromeNumber) {
largestPalindromeNumber = arr[i];
// Check for larger palindromes by examining
// subsequent numbers.
for ( int j = i + 1; j < size; j++) {
// If a larger number is found and its
// string representation has more digits,
// break the loop.
if (arr[j] > largestPalindromeNumber
&& std::to_string(arr[j]).length()
> std::to_string(
largestPalindromeNumber)
.length()) {
break ;
}
}
}
}
return largestPalindromeNumber;
} int main()
{ int arr[] = { 1, 232, 54545, 999991 };
int size = sizeof (arr) / sizeof (arr[0]);
// Find and print the largest palindrome in the array.
std::cout << "Largest Palindrome: "
<< largestPalindromeOptimized(arr, size)
<< std::endl;
return 0;
} // This code is contributed by rambabuguphka |
public class Main {
public static boolean isPalindrome( int n)
{
return Integer.toString(n).equals(
new StringBuilder(Integer.toString(n))
.reverse()
.toString());
}
public static int largestPalindromeOptimized( int [] arr)
{
int largestPalindromeNumber = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
if (isPalindrome(arr[i])
&& arr[i] > largestPalindromeNumber) {
largestPalindromeNumber = arr[i];
for ( int j = i + 1 ; j < arr.length; j++) {
if (arr[j] > largestPalindromeNumber
&& Integer.toString(arr[j]).length()
> Integer
.toString(
largestPalindromeNumber)
.length()) {
break ;
}
}
}
}
return largestPalindromeNumber;
}
public static void main(String[] args)
{
int [] arr = { 1 , 232 , 54545 , 999991 };
System.out.println(largestPalindromeOptimized(arr));
}
} |
def is_palindrome(n):
return str (n) = = str (n)[:: - 1 ]
def largest_palindrome_optimized(arr):
largest_palindrome_number = 0
for i in range ( len (arr)):
if is_palindrome(arr[i]) and arr[i] > largest_palindrome_number:
largest_palindrome_number = arr[i]
for j in range (i + 1 , len (arr)):
if arr[j] > largest_palindrome_number and len ( str (arr[j])) > len ( str (largest_palindrome_number)):
break
return largest_palindrome_number
arr = [ 1 , 232 , 54545 , 999991 ]
print (largest_palindrome_optimized(arr))
|
using System;
public class GFG {
static bool IsPalindrome( int n)
{
string str = n.ToString();
char [] charArray = str.ToCharArray();
Array.Reverse(charArray);
string reversedStr = new string (charArray);
return str == reversedStr;
}
static int LargestPalindromeOptimized( int [] arr)
{
int largestPalindromeNumber = 0;
for ( int i = 0; i < arr.Length; i++) {
if (IsPalindrome(arr[i])
&& arr[i] > largestPalindromeNumber) {
largestPalindromeNumber = arr[i];
for ( int j = i + 1; j < arr.Length; j++) {
if (arr[j] > largestPalindromeNumber
&& arr[j].ToString().Length
> largestPalindromeNumber
.ToString()
.Length) {
break ;
}
}
}
}
return largestPalindromeNumber;
}
public static void Main( string [] args)
{
int [] arr = { 1, 232, 54545, 999991 };
Console.WriteLine(LargestPalindromeOptimized(arr));
}
} |
function is_palindrome(n) {
return String(n) === String(n).split( '' ).reverse().join( '' );
} function largest_palindrome_optimized(arr) {
let largest_palindrome_number = 0;
for (let i = 0; i < arr.length; i++) {
if (is_palindrome(arr[i]) && arr[i] > largest_palindrome_number) {
largest_palindrome_number = arr[i];
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] > largest_palindrome_number && String(arr[j]).length >
String(largest_palindrome_number).length) {
break ;
}
}
}
}
return largest_palindrome_number;
} const arr = [1, 232, 54545, 999991]; console.log(largest_palindrome_optimized(arr)); |
54545
Time Complexity: The code has two nested loops, one for iterating through the array, and another for iterating through the remaining elements. However, the inner loop will only be executed for a small subset of the array elements. Therefore, the time complexity of the code is O(n*k^2), where n is the length of the array and k is the maximum number of digits in any element in the array.
Space Complexity: The code uses a constant amount of additional memory, so the space complexity is O(1).