Subarray of length K whose concatenation forms a palindrome

Given an array arr[], consisting of N integers in the range [0, 9], the task is to find a subarray of length K from which we can generate a number which is a Palindrome Number. If no such subarray exists, print -1.
Note: The elements in the array are in the range of 0 to 10.
Examples:
Input: arr[] = {1, 5, 3, 2, 3, 5, 4}, K = 5
Output: 5, 3, 2, 3, 5
Explanation:
Number generated by concatenating all elements of the subarray, i.e. 53235, is a palindrome.Input: arr[] = {2, 3, 5, 1, 3}, K = 4
Output: -1
Naive Approach: The simplest approach to solve the problem is to generate all subarrays of length K and for each subarray, concatenate all the elements from the subarray and check if the number formed is a Palindrome Number or not.Â
Time Complexity: O(N3)
Auxiliary Space: O(K)
Efficient Approach: The problem can be solved using the Window-Sliding technique. Follow the steps below to solve the problem:
- Make a palindrome function to check if the given subarray (Window-Sliding) is palindrome or not.
- Iterate over the array, and for each subarray call the palindrome function.
- If found to be true, return the starting index of that subarray, and print the array from starting index to the next k index.
- If no such subarray found which is a palindrome, print -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to check if a number// is Palindrome or not// here i is the starting index// and j is the last index of the subarraybool palindrome(vector<int> a, int i, int j){     while(i<j)     {         // If the integer at i is not equal to j         // then the subarray is not palindrome         if(a[i] != a[j])             return false;                       // Otherwise         i++;         j--;     }               // all a[i] is equal to a[j]     // then the subarray is palindrome     return true;}Â
// Function to find a subarray whose// concatenation forms a palindrome// and return its starting indexint findSubArray(vector<int> arr, int k){    int n= sizeof(arr)/sizeof(arr[0]);             // Iterating over subarray of length k    // and checking if that subarray is palindrome    for(int i=0; i<=n-k; i++){         if(palindrome(arr, i, i+k-1))             return i;    }           // If no subarray is palindrome    return -1;}Â
// Driver Codeint main(){Â Â Â Â vector<int> arr = { 2, 3, 5, 1, 3 };Â Â Â Â int k = 4;Â Â Â Â Â Â int ans = findSubArray(arr, k);Â Â Â Â Â Â if (ans == -1)Â Â Â Â Â Â Â Â Â Â cout << -1 << "\n";Â Â Â Â Â Â else {Â Â Â Â Â Â Â Â for (int i = ans; i < ans + k;Â Â Â Â Â Â Â Â Â Â Â Â Â i++)Â Â Â Â Â Â Â Â Â Â Â Â cout << arr[i] << " ";Â Â Â Â Â Â Â Â cout << "\n";Â Â Â Â }Â Â Â Â return 0;}Â
// This code is contributed by Prafulla Shekhar |
Java
// Java program for the above approachimport java.io.*;Â
class GFG {       // Function to check if a number    // is Palindrome or not    // here i is the starting index    // and j is the last index of the subarray    public static boolean palindrome(int[] a, int i, int j)    {         while(i<j)         {             // If the integer at i is not equal to j             // then the subarray is not palindrome             if(a[i] != a[j])                 return false;                           // Otherwise             i++;             j--;         }                   // all a[i] is equal to a[j]         // then the subarray is palindrome         return true;     }       // Function to find a subarray whose    // concatenation forms a palindrome    // and return its starting index    static int findSubArray(int []arr, int k)    {        int n= arr.length;                 // Iterating over subarray of length k        // and checking if that subarray is palindrome        for(int i=0; i<=n-k; i++){             if(palindrome(arr, i, i+k-1))                 return i;        }               // If no subarray is palindrome        return -1;    }Â
    // Driver code    public static void main (String[] args)     {        int []arr = { 2, 3, 5, 1, 3 };        int k = 4;          int ans = findSubArray(arr, k);          if (ans == -1)            System.out.print(-1 + "\n");          else        {            for(int i = ans; i < ans + k; i++)                System.out.print(arr[i] + " ");                          System.out.print("\n");        }    }}Â
// This code is contributed by Prafulla Shekhar |
Python3
# Python3 program for the above approachÂ
# Function to check if a number# is Palindrome or not here i is# the starting index and j is the # last index of the subarraydef palindrome(a, i, j):         while(i < j):                 # If the integer at i is not equal to j        # then the subarray is not palindrome        if (a[i] != a[j]):            return False               # Otherwise        i += 1        j -= 1         # all a[i] is equal to a[j]    # then the subarray is palindrome    return TrueÂ
# Function to find a subarray whose# concatenation forms a palindrome# and return its starting index   def findSubArray(arr, k):         n = len(arr)         # Iterating over subarray of length k    # and checking if that subarray is palindrome      for i in range(n - k + 1):        if (palindrome(arr, i, i + k - 1)):            return i         return -1Â
# Driver code   arr = [ 2, 3, 5, 1, 3 ]k = 4ans = findSubArray(arr, k)Â
if (ans == -1):Â Â Â Â print(-1)else:Â Â Â Â for i in range(ans,ans + k):Â Â Â Â Â Â Â Â print(arr[i], end = " ")Â Â Â Â Â Â Â Â Â # This code is contributed by avanitrachhadiya2155 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function to check if a number// is Palindrome or not here i is // the starting index and j is the // last index of the subarraypublic static bool palindrome(int[] a, int i,                              int j){    while (i < j)    {                 // If the integer at i is not equal to j        // then the subarray is not palindrome        if (a[i] != a[j])            return false;Â
        // Otherwise        i++;        j--;    }Â
    // All a[i] is equal to a[j]    // then the subarray is palindrome    return true;}Â
// Function to find a subarray whose// concatenation forms a palindrome// and return its starting indexstatic int findSubArray(int[] arr, int k){    int n = arr.Length;         // Iterating over subarray of length k    // and checking if that subarray is palindrome    for(int i = 0; i <= n - k; i++)     {        if (palindrome(arr, i, i + k - 1))            return i;    }Â
    // If no subarray is palindrome    return -1;}Â
// Driver codepublic static void Main(String[] args) {Â Â Â Â int[] arr = { 2, 3, 5, 1, 3 };Â Â Â Â int k = 4;Â Â Â Â int ans = findSubArray(arr, k);Â
    if (ans == -1)        Console.Write(-1 + "\n");             else    {        for(int i = ans; i < ans + k; i++)            Console.Write(arr[i] + " ");Â
        Console.Write("\n");    }}}Â
// This code is contributed by aashish1995 |
Javascript
<script>Â
// Javascript program for// the above approachÂ
    // Function to check if a number    // is Palindrome or not    // here i is the starting index    // and j is the last index of the subarray    function palindrome(a, i, j)    {         while(i<j)         {             // If the integer at i is not equal to j             // then the subarray is not palindrome             if(a[i] != a[j])                 return false;                            // Otherwise             i++;             j--;         }                    // all a[i] is equal to a[j]         // then the subarray is palindrome         return true;     }        // Function to find a subarray whose    // concatenation forms a palindrome    // and return its starting index    function findSubArray(arr, k)    {        let n= arr.length;                  // Iterating over subarray of length k        // and checking if that subarray is palindrome        for(let i=0; i<=n-k; i++){             if(palindrome(arr, i, i+k-1))                 return i;        }                // If no subarray is palindrome        return -1;    }     // Driver Code              let arr = [ 2, 3, 5, 1, 3 ];        let k = 4;           let ans = findSubArray(arr, k);           if (ans == -1)            document.write(-1 + "\n");           else        {            for(let i = ans; i < ans + k; i++)                document.write(arr[i] + " ");                           document.write("<br/>");        }Â
</script> |
-1
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



