Skip to content
Related Articles

Related Articles

Subarray of length K whose concatenation forms a palindrome
  • Difficulty Level : Basic
  • Last Updated : 15 Oct, 2020
GeeksforGeeks - Summer Carnival Banner

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 is 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:

  • Generate and store the number formed by concatenating the first K elements of the array, in a variable palin_num.
  • Check if it is a palindrome or not. If found to be true, print palin_num as the answer.
  • Otherwise, iterate over the array, and for every remaining element, append the current array element and remove the first element of the current value of palin_num. Now, check if it is a palindrome number or not.
  • If no such number could be generated 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
bool checkPalindrome(int n)
{
    int t = n, palin_num = 0;
 
    // Reversing a number
    while (t > 0) {
 
        // Append the last digit
        // of the number
        palin_num
            = palin_num * 10
              + t % 10;
 
        // Remove the last digit
        t /= 10;
    }
 
    // If the number
    // is a palindrome
    if (palin_num == n) {
        return true;
    }
 
    // Otherwise
    return false;
}
 
// Function to find a subarray whose
// concatenation forms a palindrome
// and return its starting index
int findSubArray(vector<int> arr, int k)
{
    int i, num = 0;
 
    // Concatenate first k elements
    for (i = 0; i < k; i++) {
        num = num * 10 + arr[i];
    }
 
    // Check if the first K-length
    // subarray forms a palindrome
    if (checkPalindrome(num)) {
        return 0;
    }
 
    // Traverse the array
    for (int j = i; j < arr.size(); j++) {
 
        // Append the last element of current
        // K-length subarray and remove  the
        // first element of previous subarray
        num = (num % (int)pow(
                         10, k - 1))
                  * 10
              + arr[j];
 
        // Check if the conctenation
        // forms a palindrome
        if (checkPalindrome(num)) {
            return j - k + 1;
        }
    }
    return -1;
}
 
// Driver Code
int 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;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to check if a number
// is Palindrome or not
static boolean checkPalindrome(int n)
{
    int t = n, palin_num = 0;
 
    // Reversing a number
    while (t > 0)
    {
         
        // Append the last digit
        // of the number
        palin_num = palin_num * 10 +
                            t % 10;
 
        // Remove the last digit
        t /= 10;
    }
 
    // If the number
    // is a palindrome
    if (palin_num == n)
    {
        return true;
    }
 
    // Otherwise
    return false;
}
 
// Function to find a subarray whose
// concatenation forms a palindrome
// and return its starting index
static int findSubArray(int []arr, int k)
{
    int i, num = 0;
 
    // Concatenate first k elements
    for(i = 0; i < k; i++)
    {
        num = num * 10 + arr[i];
    }
 
    // Check if the first K-length
    // subarray forms a palindrome
    if (checkPalindrome(num))
    {
        return 0;
    }
 
    // Traverse the array
    for(int j = i; j < arr.length; j++)
    {
         
        // Append the last element of current
        // K-length subarray and remove  the
        // first element of previous subarray
        num = (num % (int)Math.pow(
             10, k - 1)) * 10 + arr[j];
 
        // Check if the conctenation
        // forms a palindrome
        if (checkPalindrome(num))
        {
            return j - k + 1;
        }
    }
    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 Amit Katiyar

Python3




# Python3 program for the above approach
 
# Function to check if a number
# is Palindrome or not
def checkPalindrome(n):
     
    t = n
    palin_num = 0
 
    # Reversing a number
    while (t > 0):
 
        # Append the last digit
        # of the number
        palin_num = palin_num * 10 + t % 10
 
        # Remove the last digit
        t //= 10
 
    # If the number
    # is a palindrome
    if (palin_num == n):
        return True
 
    # Otherwise
    return False
 
# Function to find a subarray whose
# concatenation forms a palindrome
# and return its starting index
def findSubArray(arr, k):
     
    num = 0
 
    # Concatenate first k elements
    i = 0
    while i < k:
        num = num * 10 + arr[i]
        i += 1
 
    # Check if the first K-length
    # subarray forms a palindrome
    if (checkPalindrome(num)):
        return 0
 
    # Traverse the array
    for j in range(i, len(arr)):
 
        # Append the last element of current
        # K-length subarray and remove  the
        # first element of previous subarray
        num = (num % pow(10, k - 1)) * 10 + arr[j]
 
        # Check if the conctenation
        # forms a palindrome
        if (checkPalindrome(num)):
            return j - k + 1
 
    return -1
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 3, 5, 1, 3 ]
    k = 4
 
    ans = 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 mohit kumar 29

C#




// C# program for the
// above approach
using System;
class GFG{
 
// Function to check if a number
// is Palindrome or not
static bool checkPalindrome(int n)
{
  int t = n, palin_num = 0;
 
  // Reversing a number
  while (t > 0)
  {
    // Append the last digit
    // of the number
    palin_num = palin_num * 10 +
                t % 10;
 
    // Remove the last digit
    t /= 10;
  }
 
  // If the number
  // is a palindrome
  if (palin_num == n)
  {
    return true;
  }
 
  // Otherwise
  return false;
}
 
// Function to find a subarray whose
// concatenation forms a palindrome
// and return its starting index
static int findSubArray(int[] arr,
                        int k)
{
  int i, num = 0;
 
  // Concatenate first k elements
  for (i = 0; i < k; i++)
  {
    num = num * 10 + arr[i];
  }
 
  // Check if the first K-length
  // subarray forms a palindrome
  if (checkPalindrome(num))
  {
    return 0;
  }
 
  // Traverse the array
  for (int j = i; j < arr.Length; j++)
  {
    // Append the last element of current
    // K-length subarray and remove  the
    // first element of previous subarray
    num = (num % (int)Math.Pow(10,
           k - 1)) * 10 + arr[j];
 
    // Check if the conctenation
    // forms a palindrome
    if (checkPalindrome(num))
    {
      return j - k + 1;
    }
  }
  return -1;
}
 
// Driver Code
public static void Main()
{
  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 Chitranayal
Output
-1

Time Complexity: O(N2)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :