Maximum Length Palindrome of a String that can be Created with Characters in Range L and R


Introduction

A palindrome is one that reads the same forward and backward. An example of a palindrome string is Mam. In this tutorial, we use C++ programming to find the maximum length palindrome of a string by predefining the range of characters.

Our task is to find the largest length of a palindrome string using the input string. We define the range of characters to generate that string. Depending on the situation, L and R can hold any value.

Demonstration 1

String = “amem”
Range = {1,4}

Output

3

In the above demonstration, the input string is “amem” and the range to make a palindrome string is {1, 4}. This range defines the palindrome string's starting and ending values of characters. Using this range the maximum length of a palindrome string is 3 and those strings are mem, or mam.

Demonstration 2

String = “bbbb”
Range = {1, 4}

Output

4

In the above input string, the longest palindrome length within the defined range is 4. That palindrome string is bbbb.

C++ Library Function Used in Examples

Syntax

memset() : This standard library function is defined in the <cstring> header file. It sets memory blocks to particular values. It copies the values. It takes 3 parameters: ptr, val, and num. ptr is the starting address pointer, value to set, and number to set.

memset(ptr, val, num);

size() : This library function is defined in the <std> header file. It returns the size of the string.

string_name.size();

Vector: this library function is defined in the <vector> header file. It is a dynamic array in C++. It resizes itself while removing or adding elements to this array.

vector<data_type> vector_name; 

Algorithm

  • Take an input string.

  • Calculate the frequency of characters within the range using a counter variable.

  • Find both an odd and an even frequency.

  • The length of the longest palindrome spring is the summation of odd-1 and even frequency.

  • Print the results.

Example 1

We implemented one of the demonstrations using the C++ programming language. The user-defined function calculates odd and even frequencies. Sum the even and odd-1 frequencies to calculate the maximum length of the palindrome string in the defined range.

#include <bits/stdc++.h>
using namespace std;
#define N 4
 
//user-defined function to calculate frequencies
int calculateQueries(int m, int s, int p[N][26])
{
    m--;
    s--;
 
    // marking for odd frequency
    bool f = false;
 
    // counter variable to count the maximum length
    int cnt = 0;
 
    // Traversing all characters
    for (int x = 0; x < 26; x++) 
    {
        int cnt1 = p[s][x];
        if (m > 0)
            cnt1 -= p[m - 1][x];
 
        // finding odd frequencies
        if (cnt1 % 2 == 1) 
        {
            f = true;
            cnt += cnt1 - 1;
        }
     
        else
            cnt += cnt1;
    }
 
    if (f)
        cnt += 1;
 
    return cnt;
}
 
void calculateFreq(string str, int p[N][26])
{
    int m = str.size();
 
    // Iteration for counter variable
    for (int x = 0; x < m; x++)
    {
        p[x][str[x] - 'a']++;
    }
 
    for (int x = 1; x < m; x++)
    {
        for (int y = 0; y < 26; y++)
            p[x][y] += p[x - 1][y];
    }
}
 
// Code controller
int main()
{
    string str = "bbbbb";
 
    // prefix array
    int p[N][26];
    memset(p, 0, sizeof p);
    calculateFreq(str, p);
 
    int q[][2] = { 1, 4};
    int sq = sizeof(q) / sizeof(q[0]);

    for (int x = 0; x < sq; x++)
    {
        cout << calculateQueries(q[x][0],
                               q[x][1], p)
             << endl;
    }
 
    return 0;
}

Output

4

Example 2

We implemented a demonstration using C++ programming concepts. Use vectors to calculate the frequencies of palindrome characters. Create a user-defined function maxLengthPalindrome() to find the required length of palindrome string within {1, 4}.

You can change the input string and range as per your needs.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int maxLengthPalindrome(string& s, int st, int e) 
{
    // Initialize a vector to store the frequency of each character
    vector<int> freq(26, 0);

    // Count the frequency of characters within the given range
    for (int x = st - 1; x <= e - 1; x++)
    {
        freq[s[x] - 'a']++;
    }

    int l = 0;
    bool oddFreq = false;

    // Calculate the maximum length palindrome
    for (int x = 0; x < 26; x++)
    {
        l += freq[x] / 2 * 2;
        
        if (freq[x] % 2 == 1) 
        {
            oddFreq = true;
        }
    }

    // If there is a character with an odd frequency, increment the length by 1
    if (oddFreq) 
    {
        l++;
    }

    return l;
}

int main() 
{
    string s = "amem";
    int st = 1;
    int e = 4;

    int maxLen = maxLengthPalindrome(s, st, e);

    cout << "Maximum length palindrome: " << maxLen << endl;

    return 0;
}

Output

Maximum length palindrome: 3

Conclusion

We reached the end of this tutorial to find the maximum length palindrome string within the given range. We implemented two different examples to solve the task. The demonstrations help us understand the problem statement requirements. We defined the range to generate the maximum length palindrome string using the input string. The C++ implementation used different C++ library functions to make the problem easy.

Updated on: 18-Aug-2023

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements