Find the longest cyclic String with no adjacent identical characters
Last Updated :
21 Oct, 2023
Given an array of size N containing N number of cyclic strings each containing characters ‘P’ and ‘R’ in some order. A string is said to be special if there are no pairs of adjacent elements with identical characters, the task is to return the index of the special string with the maximum number of characters, if there are none then return -1. We can perform the following operation on a string only once.
- Make two cuts on the string, splitting it into three parts.
- Reverse one of these parts.
- Combine together the corresponding endpoints of the two parts, creating one whole string again.
Examples:
Input: arr[]= [“PPRR”, “PR”, “PPRRPR”], N = 3
Output: 2
Explanation: The special string with the maximum number of characters is “PPRRPR”, we can apply the operation and convert it into PRPRPR, by cutting it by index-1 and index-3 and reversing it.
Input: arr[] = [“PPPP”, “PPPPRR”, “PRRR”], N = 3
Output: -1
Explanation: None of them can be converted to a Special string.
Approach: To solve the problem follow the below idea:
The idea is to check number of pairs where s[i] == s[i+1] and we can make string special if number of pairs are less than or equal to 2 also number of P ‘s and R’s should be same else we can not make it special also string with odd length can never be special. after checking these condition find out the maximum length special string.
To solve this problem, we can follow these steps:
- Initialize variables:
- Set ans to -1, which will store the index of the longest special string.
- Set maxCharacters to 0, which will keep track of the maximum number of characters in a special string.
- Iterate through each string in the given array:
- Let s be the current string.
- Initialize the following counters:
- countPs to count the number of ‘P’ characters in the string.
- countRs to count the number of ‘R’ characters in the string.
- countPairs to count the number of pairs with identical adjacent characters.
- flag as a boolean variable to check if the string is special.
- Check if the number of characters in the string is odd:
- If s.size() % 2 == 1, set flag to false, as special strings should have an even number of characters.
- Iterate through each character in the string:
- Increment countPs if the current character is ‘P’.
- Increment countRs if the current character is ‘R’.
- Check if the current character is the same as the previous character (for non-first characters).
- If true, increment countPairs.
- Check if the first and last characters of the string are the same:
- If s.size() > 2 and s[0] == s[s.size() – 1], increment countPairs.
- Check if the string is special:
- If countRs != countPs or countPairs > 2, set flag to false.
- Check if the string is special and has more characters than the current maximum:
- If flag is true and s.size() > maxCharacters, update maxCharacters with s.size() and set ans to the current index.
- Return ans as the index of the longest special string or -1 if there is no such string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int bestString(vector<string>& arr, int n)
{
int ans = -1;
int maxStones = 0;
for ( int it = 0; it < n; it++) {
string s = arr[it];
int countPs = 0;
int countRs = 0;
int countPairs = 0;
bool flag = true ;
if (s.size() % 2 == 1) {
flag = false ;
}
for ( int i = 0; i < s.size(); i++) {
if (s[i] == 'R' ) {
countRs++;
}
else {
countPs++;
}
if (i > 0 and s[i] == s[i - 1]) {
countPairs++;
}
}
if (s.size() > 2 and s[0] == s[s.size() - 1]) {
countPairs++;
}
if (countRs != countPs or countPairs > 2) {
flag = false ;
}
if (flag == true and s.size() > maxStones) {
maxStones = s.size();
ans = it;
}
}
return ans;
}
int main()
{
vector<string> arr;
arr.push_back( "PPRR" );
arr.push_back( "PR" );
arr.push_back( "PPRRPR" );
cout << "Index of Special String with maximum number "
"of characters is: "
<< bestString(arr, arr.size());
return 0;
}
|
Java
import java.util.ArrayList;
class SpecialString {
static int bestString(ArrayList<String> arr, int n) {
int ans = - 1 ;
int maxStones = 0 ;
for ( int it = 0 ; it < n; it++) {
String s = arr.get(it);
int countPs = 0 ;
int countRs = 0 ;
int countPairs = 0 ;
boolean flag = true ;
if (s.length() % 2 == 1 ) {
flag = false ;
}
for ( int i = 0 ; i < s.length(); i++) {
if (s.charAt(i) == 'R' ) {
countRs++;
} else {
countPs++;
}
if (i > 0 && s.charAt(i) == s.charAt(i - 1 )) {
countPairs++;
}
}
if (s.length() > 2 && s.charAt( 0 ) == s.charAt(s.length() - 1 )) {
countPairs++;
}
if (countRs != countPs || countPairs > 2 ) {
flag = false ;
}
if (flag && s.length() > maxStones) {
maxStones = s.length();
ans = it;
}
}
return ans;
}
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<>();
arr.add( "PPRR" );
arr.add( "PR" );
arr.add( "PPRRPR" );
System.out.println( "Index of Special String with maximum number " +
"of characters is: " + bestString(arr, arr.size()));
}
}
|
Python
def best_string(arr):
ans = - 1
max_stones = 0
for idx, s in enumerate (arr):
count_ps = 0
count_rs = 0
count_pairs = 0
flag = True
if len (s) % 2 = = 1 :
flag = False
for i in range ( len (s)):
if s[i] = = 'R' :
count_rs + = 1
else :
count_ps + = 1
if i > 0 and s[i] = = s[i - 1 ]:
count_pairs + = 1
if len (s) > 2 and s[ 0 ] = = s[ - 1 ]:
count_pairs + = 1
if count_rs ! = count_ps or count_pairs > 2 :
flag = False
if flag and len (s) > max_stones:
max_stones = len (s)
ans = idx
return ans
if __name__ = = "__main__" :
arr = [ "PPRR" , "PR" , "PPRRPR" ]
print ( "Index of Special String with maximum number "
"of characters is:" , best_string(arr))
|
C#
using System;
using System.Collections.Generic;
class SpecialString
{
static int BestString(List< string > arr, int n)
{
int ans = -1;
int maxStones = 0;
for ( int it = 0; it < n; it++)
{
string s = arr[it];
int countPs = 0;
int countRs = 0;
int countPairs = 0;
bool flag = true ;
if (s.Length % 2 == 1)
{
flag = false ;
}
for ( int i = 0; i < s.Length; i++)
{
if (s[i] == 'R' )
{
countRs++;
}
else
{
countPs++;
}
if (i > 0 && s[i] == s[i - 1])
{
countPairs++;
}
}
if (s.Length > 2 && s[0] == s[s.Length - 1])
{
countPairs++;
}
if (countRs != countPs || countPairs > 2)
{
flag = false ;
}
if (flag && s.Length > maxStones)
{
maxStones = s.Length;
ans = it;
}
}
return ans;
}
public static void Main( string [] args)
{
List< string > arr = new List< string >();
arr.Add( "PPRR" );
arr.Add( "PR" );
arr.Add( "PPRRPR" );
Console.WriteLine( "Index of Special String with maximum number " +
"of characters is: " + BestString(arr, arr.Count));
}
}
|
Javascript
function bestString(arr) {
let ans = -1;
let maxStones = 0;
for (let it = 0; it < arr.length; it++) {
let s = arr[it];
let countPs = 0;
let countRs = 0;
let countPairs = 0;
let flag = true ;
if (s.length % 2 === 1) {
flag = false ;
}
for (let i = 0; i < s.length; i++) {
if (s[i] === 'R' ) {
countRs++;
} else {
countPs++;
}
if (i > 0 && s[i] === s[i - 1]) {
countPairs++;
}
}
if (s.length > 2 && s[0] === s[s.length - 1]) {
countPairs++;
}
if (countRs !== countPs || countPairs > 2) {
flag = false ;
}
if (flag && s.length > maxStones) {
maxStones = s.length;
ans = it;
}
}
return ans;
}
const arr = [ "PPRR" , "PR" , "PPRRPR" ];
const resultIndex = bestString(arr);
console.log(`Index of the special string with the maximum number of characters is: ${resultIndex}`);
|
Output
Index of Special String with maximum number of characters is: 2
Time Complexity: O(N*S)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...