# Two Characters – HackerRank Solution

In this post, we will solve Two Characters HackerRank Solution. This problem (Two Characters) is a part of HackerRank Problem Solving series.

Given a string, remove characters until the string is made up of any two alternating characters. When you choose a character to remove, all instances of that character must be removed. Determine the longest string possible that contains just two alternating letters.

Example

s = ‘abaacdabd’

DeleteÂ `a`, to leaveÂ `bcdbd`. Now, remove the characterÂ `c`Â to leave the valid stringÂ `bdbd`Â with a length of 4. Removing eitherÂ `b`Â orÂ `d`Â at any point would not result in a valid string. ReturnÂ 4.

Given a stringÂ s, convert it to the longest possible stringÂ tÂ made up only of alternating characters. Return the length of stringÂ t. If no stringÂ tÂ can be formed, returnÂ 0.

Function Description

Complete the alternate function in the editor below.

alternate has the following parameter(s):

• string s: a string

Returns.

• int:Â the length of the longest valid string, orÂ 0Â if there are none

## Input Format

The first line contains a single integer that denotes the length ofÂ s.
The second line contains stringÂ s.

## Constraints

• 1 <= length of s <= 1000
• s[i] âˆˆ ascii[a – z]

Sample Input

``````STDIN       Function
-----       --------
10          length of s = 10
beabeefeab  s = 'beabeefeab'``````

Sample Output

``5``

Explanation

The characters present inÂ sÂ areÂ `a`,Â `b`,Â `e`, andÂ `f`. This means thatÂ tÂ must consist ofÂ twoÂ of those characters and we must deleteÂ twoÂ others. Our choices for characters to leave are [a,b], [a,e], [a, f], [b, e], [b, f] and [e, f].

If we deleteÂ `e`Â andÂ `f`, the resulting string isÂ `babab`. This is a validÂ tÂ as there are only two distinct characters (`a`Â andÂ `b`), and they are alternating within the string.

If we deleteÂ `a`Â andÂ `f`, the resulting string isÂ `bebeeeb`. This is not a valid stringÂ tÂ because there are consecutiveÂ `e`‘s present. Removing them would leave consecutiveÂ `b's`, so this fails to produce a valid stringÂ t.

Other cases are solved similarly.

`babab`Â is the longest string we can create.

## Solution – Two Characters – HackerRank Solution

### C++

```#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

int main() {
int n; std::cin >> n; /* useless to us, but whatever... */
std::string s; std::cin >> s;

std::vector<int> freq(26,0);
for (const char& c : s) freq[c-'a']++;

int max = 0;
char last;
bool valid;

for (int i = 0; i < freq.size(); i++) {
if (freq[i] == 0) continue;

for (int j = i+1; j < freq.size(); j++) {

if (freq[j] == 0) continue;

last = -1;
valid = true;
for (const char& c : s) {
if (c == char(i+'a') || c == char(j+'a')) {
if (last == c) {
valid = false;
break;
}
last = c;
}
}

if (valid && std::abs(freq[i] - freq[j]) <= 1)
max = std::max(max, freq[i] + freq[j]);
}
}
std::cout << max << std::endl;

return 0;
}
```

### Python

```import sys
from itertools import combinations

def validate(string):
for ind in range(len(string)-1):
if string[ind] == string[ind + 1]:
return False
return True

def twoCharaters(string):
str_set = set(list(string))
variants = combinations(str_set, 2)
max_res = 0

for comb in variants:
t = [c for c in string if c == comb[0] or c == comb[1]]
#print("comb = {} t = {}".format(comb, t))
if validate(t):
max_res = max(max_res, len(t))

return max_res

if __name__ == "__main__":
l = int(input().strip())
s = input().strip()
result = twoCharaters(s)
print(result)
```

### Java

```import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int len = in.nextInt();
String s = in.next();
int maxPattern = 0;

if(s.length() == 1)//Edge case where length is 1
{
System.out.println(maxPattern);
System.exit(0);
}

//Loop through all letter pairs
for(int i = 0; i < 26; i++)
{
nextLetter:
for(int j = i + 1; j < 26; j++)
{
char one = (char) ('a' + i); //First char in pair
char two = (char) ('a' + j); //Second char in pair
char lastSeen = '\u0000';
int patternLength = 0;

for(char letter : s.toCharArray())
{
if(letter == one || letter == two)
{
if(letter == lastSeen)//Duplicate found
{
continue nextLetter;
}
//Not a duplicate
patternLength++;
lastSeen = letter;
}
}//for char : s

maxPattern = (patternLength > maxPattern) ? patternLength : maxPattern; //Keep a running max

}//for j
}//for i

System.out.println(maxPattern);

}
}
```

Note: This problem (Two Characters) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.