Check if any subarray can be made palindromic by replacing less than half of its elements

• Difficulty Level : Medium
• Last Updated : 19 May, 2021

Given an array arr[] of size N, the task is to check if any subarray from the given array can be made a palindrome by replacing less than half of its elements (i.e. floor[length/2]) by any other element of the subarray.

Examples:

Input: arr[] = {2, 7, 4, 6, 7, 8}
Output: Yes
Explanation: Among all subarrays of this array, subarray {7, 4, 6, 7} requires only 1 operation to make it a palindrome i.e. replace arr by 4 or arr by 6, which is less than floor(4/2) ( = 2).

Input: arr[] = {3, 7, 19, 6}
Output: No

Naive Approach: The simplest approach to solve this problem is to generate all subarrays of the given array and for each subarray, check if the number of replacements required to make that subarray a palindrome is less than floor(length of subarray / 2)

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

Efficient Approach: The above approach can be optimized based on the following observations:

If the array arr[] contains duplicate elements, then it is always possible to choose a subarray from initial occurrence to the next occurrence of that element. This subarray will require less than floor(length/2) operations as first and last element of subarray is already equal.

Follow the steps below to solve the problem:

Below is the implementation of this approach:

C++

 // C++ program for the above approach #include using namespace std; // A Utility Function to check if a subarray// can be palindromic by replacing less than// half of the elements present in itbool isConsistingSubarrayUtil(int arr[], int n){    // Stores frequency of array elements    map mp;     // Traverse the array    for (int i = 0; i < n; ++i) {         // Update frequency of        // each array element        mp[arr[i]]++;    }     // Iterator over the Map    map::iterator it;     for (it = mp.begin(); it != mp.end(); ++it) {         // If frequency of any element exceeds 1        if (it->second > 1) {            return true;        }    }     // If no repetition is found    return false;} // Function to check and print if any subarray// can be made palindromic by replacing less// than half of its elementsvoid isConsistingSubarray(int arr[], int N){    if (isConsistingSubarrayUtil(arr, N)) {        cout << "Yes" << endl;    }    else {        cout << "No" << endl;    }} // Driver Codeint main(){    // Given array arr[]    int arr[] = { 1, 2, 3, 4, 5, 1 };     // Size of array    int N = sizeof(arr) / sizeof(arr);     // Function Call    isConsistingSubarray(arr, N);     return 0;}

Java

 // Java program for the above approachimport java.util.*;  class GFG{     // A Utility Function to check if a subarray// can be palindromic by replacing less than// half of the elements present in itstatic boolean isConsistingSubarrayUtil(int arr[],                                        int n){         // Stores frequency of array elements    TreeMap mp = new TreeMap();      // Traverse the array    for(int i = 0; i < n; ++i)    {                 // Update frequency of        // each array element        mp.put(arr[i],        mp.getOrDefault(arr[i], 0) + 1);    }         for(Map.Entry it : mp.entrySet())    {                 // If frequency of any element exceeds 1        if (it.getValue() > 1)        {            return true;        }    }         // If no repetition is found    return false;}  // Function to check and print if any subarray// can be made palindromic by replacing less// than half of its elementsstatic void isConsistingSubarray(int arr[], int N){    if (isConsistingSubarrayUtil(arr, N))    {        System.out.println("Yes");    }    else    {        System.out.println("No");    }}  // Driver Codepublic static void main(String args[]){         // Given array arr[]    int arr[] = { 1, 2, 3, 4, 5, 1 };         // Size of array    int N = arr.length;         // Function Call    isConsistingSubarray(arr, N);}} // This code is contributed by susmitakundugoaldanga

Python3

 # Python3 program for the above approach # A Utility Function to check if a subarray# can be palindromic by replacing less than# half of the elements present in itdef isConsistingSubarrayUtil(arr, n) :     # Stores frequency of array elements    mp = {};     # Traverse the array    for i in range(n) :         # Update frequency of        # each array element        if arr[i] in mp :            mp[arr[i]] += 1;                   else :            mp[arr[i]] = 1;     # Iterator over the Map    for it in mp :         # If frequency of any element exceeds 1        if (mp[it] > 1) :            return True;     # If no repetition is found    return False; # Function to check and print if any subarray# can be made palindromic by replacing less# than half of its elementsdef isConsistingSubarray(arr, N) :     if (isConsistingSubarrayUtil(arr, N)) :        print("Yes");    else :        print("No"); # Driver Codeif __name__ == "__main__" :     # Given array arr[]    arr = [ 1, 2, 3, 4, 5, 1 ];     # Size of array    N = len(arr);     # Function Call    isConsistingSubarray(arr, N);     # This code is contributed by AnkThon

C#

 // C# program for the above approachusing System;using System.Collections.Generic;using System.Linq;     class GFG{     // A Utility Function to check if a subarray// can be palindromic by replacing less than// half of the elements present in itstatic bool isConsistingSubarrayUtil(int[] arr,                                        int n){          // Stores frequency of array elements    Dictionary mp = new Dictionary();       // Traverse the array    for(int i = 0; i < n; ++i)    {                  // Update frequency of        // each array element        if (mp.ContainsKey(arr[i]) == true)        mp[arr[i]] += 1;      else        mp[arr[i]] = 1;    }         var val = mp.Keys.ToList();    foreach(var key in val)    {        // If frequency of any element exceeds 1        if (mp[key] > 1)        {            return true;        }    }          // If no repetition is found    return false;}   // Function to check and print if any subarray// can be made palindromic by replacing less// than half of its elementsstatic void isConsistingSubarray(int[] arr, int N){    if (isConsistingSubarrayUtil(arr, N))    {        Console.Write("Yes");    }    else    {        Console.Write("No");    }}     // Driver Codepublic static void Main(){    // Given array arr[]    int[] arr = { 1, 2, 3, 4, 5, 1 };          // Size of array    int N = arr.Length;          // Function Call    isConsistingSubarray(arr, N);}} // This code is contributed by sanjoy62

Javascript


Output:
Yes

Time Complexity: O(N)
Auxiliary Space:  O(N)

My Personal Notes arrow_drop_up