Given is an array Arr of integers. The task is to determine if the array has any subsequence of at least length 3 that is a palindrome.
Examples:
Input: Arr[] = [1, 2, 1]
Output: YES
Explanation: Here 1 2 1 is a palindrome.
Input: Arr[] = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
Output: NO
Explanation: Here no subsequence of length at least 3 exists which is a palindrome.
Approach:
- The idea is to check only for length 3 because if a palindromic subsequence of length greater than 3 exists then there is always a palindromic subsequence of length 3.
- To find the palindromic subsequence of length 3 we just need to find a pair of equal non-adjacent number.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
string SubPalindrome( int n, int arr[])
{
bool ok = false ;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 2; j < n; j++)
{
if (arr[i] == arr[j])
ok = true ;
}
}
if (ok)
return "YES" ;
else
return "NO" ;
}
int main()
{
int Arr[] = {1, 2, 2, 3, 2};
int N = sizeof (Arr)/ sizeof (Arr[0]);
cout << SubPalindrome(N, Arr);
}
|
Java
import java.util.*;
class GFG{
static String SubPalindrome( int n, int arr[])
{
boolean ok = false ;
for ( int i = 0 ; i < n; i++)
{
for ( int j = i + 2 ; j < n; j++)
{
if (arr[i] == arr[j])
ok = true ;
}
}
if (ok)
return "YES" ;
else
return "NO" ;
}
public static void main(String[] args)
{
int Arr[] = { 1 , 2 , 2 , 3 , 2 };
int N = Arr.length;
System.out.print(SubPalindrome(N, Arr));
}
}
|
Python3
def SubPalindrome (n, arr):
ok = False
for i in range (n):
for j in range (i + 2 , n):
if arr[i] = = arr[j]:
ok = True
return ( 'YES' if ok else 'NO' )
Arr = [ 1 , 2 , 2 , 3 , 2 ]
N = len (arr)
print (SubPalindrome(N, Arr))
|
C#
using System;
public class GFG{
static string SubPalindrome( int n, int []arr)
{
bool ok = false ;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 2; j < n; j++)
{
if (arr[i] == arr[j])
ok = true ;
}
}
if (ok)
return "YES" ;
else
return "NO" ;
}
static public void Main ()
{
int []Arr = { 1, 2, 2, 3, 2 };
int N = Arr.Length;
Console.WriteLine(SubPalindrome(N, Arr));
}
}
|
Javascript
<script>
function SubPalindrome(n, arr)
{
let ok = false ;
for (let i = 0; i < n; i++)
{
for (let j = i + 2; j < n; j++)
{
if (arr[i] == arr[j])
ok = true ;
}
}
if (ok)
return "YES" ;
else
return "NO" ;
}
let Arr = [1, 2, 2, 3, 2];
let N = Arr.length;
document.write(SubPalindrome(N, Arr));
</script>
|
Time Complexity: O(N^2)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
19 Sep, 2022
Like Article
Save Article