Open In App

Minimum length of substring whose rotation generates a palindromic substring

Last Updated : 16 Jun, 2022
Comments
Improve
Suggest changes
1 Like
Like
Report

Given a string str, the task is to find the minimum length of substring required to rotate that generates a palindromic substring from the given string.


Examples: 

Input: str = "abcbd" 
Output:
Explanation: No palindromic substring can be generated. There is no repeated character in the string.
 

Input: str = "abcdeba" 
Output:
Explanation: Rotate substring "deb" to convert the given string to abcbeda with a palindromic substring "bcb". 

Approach: 

  • If no character repeats in the string, then no palindromic substring can be generated.
  • For every repeating character, check if the index of its previous occurrence is within one or two indices from the current index. If so, then a palindromic substring already exists.
  • Otherwise, calculate the length of (current index - index of the previous occurrence - 1).
  • Return the minimum of all such lengths as the answer

Below is the implementation of the above approach: 

C++
// C++ Program to find the minimum
// length of substring whose rotation
// generates a palindromic substring

#include <bits/stdc++.h>
using namespace std;

// Function to return the
// minimum length of substring
int count_min_length(string s)
{

    // Store the index of
    // previous occurrence
    // of the character
    int hash[26];

    // Variable to store
    // the maximum length
    // of substring
    int ans = INT_MAX;

    for (int i = 0; i < 26; i++)
        hash[i] = -1;

    for (int i = 0; i < s.size(); i++) {
        // If the current character
        // hasn't appeared yet
        if (hash[s[i] - 'a'] == -1)
            hash[s[i] - 'a'] = i;
        else {
            // If the character has occurred
            // within one or two previous
            // index, a palindromic substring
            // already exists
            if (hash[s[i] - 'a'] == i - 1
                || hash[s[i] - 'a'] == i - 2)
                return 0;

            // Update the maximum
            ans = min(ans,
                      i - hash[s[i] - 'a'] - 1);

            // Replace the previous
            // index of the character by
            // the current index
            hash[s[i] - 'a'] = i;
        }
    }

    // If character appeared
    // at least twice
    if (ans == INT_MAX)
        return -1;

    return ans;
}
// Driver Code
int main()
{
    string str = "abcdeba";
    cout << count_min_length(str);
}
Java Python3 C# JavaScript

Output: 
3

 

Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time 
Auxiliary Space: O(26), as we are using  extra space for hash.
 


Next Article

Similar Reads