# Find the longest cyclic String with no adjacent identical characters

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++

 `// C++ implimentation of above idea``#include ``using` `namespace` `std;` `// Function to get the Special String``// with maximum number of characters``int` `bestString(vector& arr, ``int` `n)``{` `    ``// Variable to store the index of the best string``    ``int` `ans = -1;` `    ``// Variable to check which string``    ``// has the maximum number of characters``    ``int` `maxStones = 0;` `    ``for` `(``int` `it = 0; it < n; it++) {` `        ``string s = arr[it];` `        ``// Counter variable to count the``        ``// number of P's in string``        ``int` `countPs = 0;` `        ``// Counter variable to count the``        ``// number of R's in the string.``        ``int` `countRs = 0;` `        ``// Counter variable to count the``        ``// number of pairs with same``        ``// adjacent character in the string``        ``int` `countPairs = 0;` `        ``// Boolean variable to check if the``        ``// string is special.``        ``bool` `flag = ``true``;` `        ``// If the number of characters in``        ``// the bracelet are odd then``        ``// initialise the boolean variable``        ``// with false``        ``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++;``            ``}``        ``}` `        ``// As the string is circular we``        ``// also need to check the first``        ``// and last characters``        ``if` `(s.size() > 2 and s[0] == s[s.size() - 1]) {` `            ``countPairs++;``        ``}` `        ``// If number of R's and P's are``        ``// not same or the number of pairs``        ``// of same adjacent characters are``        ``// more than one, then it is``        ``// not Special``        ``if` `(countRs != countPs or countPairs > 2) {``            ``flag = ``false``;``        ``}` `        ``if` `(flag == ``true` `and s.size() > maxStones) {``            ``maxStones = s.size();``            ``ans = it;``        ``}``    ``}` `    ``return` `ans;``}` `// Drivers code``int` `main()``{``    ``vector arr;``    ``arr.push_back(``"PPRR"``);``    ``arr.push_back(``"PR"``);``    ``arr.push_back(``"PPRRPR"``);` `    ``// Function call``    ``cout << ``"Index of Special String with maximum number "``            ``"of characters is: "``        ``<< bestString(arr, arr.size());` `    ``return` `0;``}`

## Java

 `import` `java.util.ArrayList;` `class` `SpecialString {``    ``// Function to get the Special String``    ``// with the maximum number of characters``    ``static` `int` `bestString(ArrayList arr, ``int` `n) {``        ``// Variable to store the index of the best string``        ``int` `ans = -``1``;` `        ``// Variable to check which string``        ``// has the maximum number of characters``        ``int` `maxStones = ``0``;` `        ``for` `(``int` `it = ``0``; it < n; it++) {``            ``String s = arr.get(it);` `            ``// Counter variable to count the``            ``// number of P's in the string``            ``int` `countPs = ``0``;` `            ``// Counter variable to count the``            ``// number of R's in the string.``            ``int` `countRs = ``0``;` `            ``// Counter variable to count the``            ``// number of pairs with the same``            ``// adjacent character in the string``            ``int` `countPairs = ``0``;` `            ``// Boolean variable to check if the``            ``// string is special.``            ``boolean` `flag = ``true``;` `            ``// If the number of characters in``            ``// the bracelet is odd then``            ``// initialize the boolean variable``            ``// with false``            ``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++;``                ``}``            ``}` `            ``// As the string is circular, we``            ``// also need to check the first``            ``// and last characters``            ``if` `(s.length() > ``2` `&& s.charAt(``0``) == s.charAt(s.length() - ``1``)) {``                ``countPairs++;``            ``}` `            ``// If the number of R's and P's are``            ``// not the same or the number of pairs``            ``// of the same adjacent characters are``            ``// more than one, then it is not Special``            ``if` `(countRs != countPs || countPairs > ``2``) {``                ``flag = ``false``;``            ``}` `            ``if` `(flag && s.length() > maxStones) {``                ``maxStones = s.length();``                ``ans = it;``            ``}``        ``}` `        ``return` `ans;``    ``}` `    ``// Drivers code``    ``public` `static` `void` `main(String[] args) {``        ``ArrayList arr = ``new` `ArrayList<>();``        ``arr.add(``"PPRR"``);``        ``arr.add(``"PR"``);``        ``arr.add(``"PPRRPR"``);` `        ``// Function call``        ``System.out.println(``"Index of Special String with maximum number "` `+``                ``"of characters is: "` `+ bestString(arr, arr.size()));``    ``}``}``// This code is contributed by shivamgupta0987654321`

## Python

 `# Python implementation of above approach``def` `best_string(arr):``    ``# Variable to store the index of the best string``    ``ans ``=` `-``1` `    ``# Variable to check which string``    ``# has the maximum number of characters``    ``max_stones ``=` `0` `    ``for` `idx, s ``in` `enumerate``(arr):``        ``# Counter variable to count the``        ``# number of P's in string``        ``count_ps ``=` `0` `        ``# Counter variable to count the``        ``# number of R's in the string.``        ``count_rs ``=` `0` `        ``# Counter variable to count the``        ``# number of pairs with the same``        ``# adjacent character in the string``        ``count_pairs ``=` `0` `        ``# Boolean variable to check if the``        ``# string is special.``        ``flag ``=` `True` `        ``# If the number of characters in``        ``# the bracelet are odd, then``        ``# initialize the boolean variable``        ``# with False``        ``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` `        ``# As the string is circular, we``        ``# also need to check the first``        ``# and last characters``        ``if` `len``(s) > ``2` `and` `s[``0``] ``=``=` `s[``-``1``]:``            ``count_pairs ``+``=` `1` `        ``# If the number of R's and P's are``        ``# not the same or the number of pairs``        ``# of the same adjacent characters are``        ``# more than one, then it is not Special``        ``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` `# Drivers code``if` `__name__ ``=``=` `"__main__"``:``    ``arr ``=` `[``"PPRR"``, ``"PR"``, ``"PPRRPR"``]` `    ``# Function call``    ``print``(``"Index of Special String with maximum number "``          ``"of characters is:"``, best_string(arr))``    ` ` ``# this code is cocntributed by uttamdp_10`

## C#

 `// C# implementation of the above approach``using` `System;``using` `System.Collections.Generic;` `class` `SpecialString``{``    ``// Function to get the Special String``    ``// with the maximum number of characters``    ``static` `int` `BestString(List<``string``> arr, ``int` `n)``    ``{``        ``// Variable to store the index of the best string``        ``int` `ans = -1;` `        ``// Variable to check which string``        ``// has the maximum number of characters``        ``int` `maxStones = 0;` `        ``for` `(``int` `it = 0; it < n; it++)``        ``{``            ``string` `s = arr[it];` `            ``// Counter variable to count the``            ``// number of P's in the string``            ``int` `countPs = 0;` `            ``// Counter variable to count the``            ``// number of R's in the string.``            ``int` `countRs = 0;` `            ``// Counter variable to count the``            ``// number of pairs with the same``            ``// adjacent character in the string``            ``int` `countPairs = 0;` `            ``// Boolean variable to check if the``            ``// string is special.``            ``bool` `flag = ``true``;` `            ``// If the number of characters in``            ``// the bracelet is odd then``            ``// initialize the boolean variable``            ``// with false``            ``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++;``                ``}``            ``}` `            ``// As the string is circular, we``            ``// also need to check the first``            ``// and last characters``            ``if` `(s.Length > 2 && s[0] == s[s.Length - 1])``            ``{``                ``countPairs++;``            ``}` `            ``// If the number of R's and P's are``            ``// not the same or the number of pairs``            ``// of the same adjacent characters are``            ``// more than one, then it is not Special``            ``if` `(countRs != countPs || countPairs > 2)``            ``{``                ``flag = ``false``;``            ``}` `            ``if` `(flag && s.Length > maxStones)``            ``{``                ``maxStones = s.Length;``                ``ans = it;``            ``}``        ``}` `        ``return` `ans;``    ``}` `    ``// Drivers code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``List<``string``> arr = ``new` `List<``string``>();``        ``arr.Add(``"PPRR"``);``        ``arr.Add(``"PR"``);``        ``arr.Add(``"PPRRPR"``);` `        ``// Function call``        ``Console.WriteLine(``"Index of Special String with maximum number "` `+``            ``"of characters is: "` `+ BestString(arr, arr.Count));``    ``}``}` `// This code is contributed by Sakshi`

## Javascript

 `// Function to find the special string with the maximum number of characters``function` `bestString(arr) {``    ``let ans = -1; ``// Variable to store the index of the best string``    ``let maxStones = 0; ``// Variable to keep track of the maximum number of characters` `    ``for` `(let it = 0; it < arr.length; it++) {``        ``let s = arr[it]; ``// Current string being considered` `        ``let countPs = 0; ``// Counter variable to count the number of 'P's in the string``        ``let countRs = 0; ``// Counter variable to count the number of 'R's in the string``        ``let countPairs = 0; ``// Counter variable to count the number of adjacent character pairs``        ``let flag = ``true``; ``// Boolean variable to check if the string is special` `        ``// If the number of characters in the bracelet is odd, initialize the flag with false``        ``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++;``            ``}``        ``}` `        ``// Check the first and last characters because the string is circular``        ``if` `(s.length > 2 && s[0] === s[s.length - 1]) {``            ``countPairs++;``        ``}` `        ``// If the number of 'R's and 'P's are not the same or there are more than two pairs of adjacent characters, it's not special``        ``if` `(countRs !== countPs || countPairs > 2) {``            ``flag = ``false``;``        ``}` `        ``if` `(flag && s.length > maxStones) {``            ``maxStones = s.length;``            ``ans = it;``        ``}``    ``}` `    ``return` `ans;``}` `// Driver code``const arr = [``"PPRR"``, ``"PR"``, ``"PPRRPR"``];` `// Function call``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)

Previous
Next