# HackerRank Two Characters Solution

#### ByBrokenprogrammers

Dec 13, 2022

Hello Programmers, In this post, you will learn how to solve HackerRank Two Characters Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

## HackerRank Two Characters Solution

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 abe, 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.

babab is the longest string we can create.

Explanation 2

baab → bb → Empty String

## HackerRank Two Characters Solution

### Two Characters Solution in C

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main(){
int len;
scanf("%d",&len);
char* s = (char *)malloc(512000 * sizeof(char));
scanf("%s",s);
if(len==1)
{
printf("0");
return 0;
}
int maxlen=0;
for(int i='a'; i<='z'; i++)
for(char j='a'; j<='z'; j++)
{
if(i==j)
continue;
char target = i;
char ntarget = j;
int slen=0;
for(int k=0; k<len; k++)
{
if(s[k]==target)
{
slen ++;

target = (target==i)?j:i;
ntarget = (target==i)?j:i;
continue;
}
if(s[k] == ntarget)
{
slen = 0;
break;
}
}
maxlen = (maxlen>slen)?maxlen:slen;
}

printf("%d", maxlen);

return 0;
}

### Two Characters Solution in Cpp

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> ii;
int valid(string x) {
const int n = x.size();
for (int i = 1; i < n; ++i)
if (x[i] == x[i-1])
return false;
return true;
}
int main() {
int asd;
cin>>asd;
string s;
cin>>s;
int ans = 0;
for (char a = 'a'; a <= 'z'; ++a)
for (char b = 'a'; b <= 'z'; ++b)
if (a != b)
{
if (s.find(a) == string::npos) continue;
if (s.find(b) == string::npos) continue;
string x;
for (const char ch : s)
if (ch == a || ch == b)
x.push_back(ch);
if (valid(x))
ans = max(ans, (int)x.size());
}
printf("%d\n", ans);
}

### Two Characters Solution in 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 n=in.nextInt();
String s=in.next();
String res="";
for(int i=0;i<26;i++){
for(int j=i+1;j<26;j++){
char a=(char)('a'+i);
char b=(char)('a'+j);
String cur="";
for(int k=0;k<n;k++){
if (s.charAt(k)==a || s.charAt(k)==b) {
cur+=s.charAt(k);
}
}
if (cur.length()<res.length()) continue;
if (isGood(cur)) res=cur;
}
}
System.out.println(res.length());
}
public static boolean isGood(String s){
if (s.length()==1) return false;
for(int i=1;i<s.length();i++){
if (s.charAt(i)==s.charAt(i-1)) return false;
}
return true;
}
}

### Two Characters Solution in Python

from collections import Counter
from itertools import combinations
def is_valid(S):
c = Counter(S)
#print c
if len(c) != 2:
return False
for i in xrange(1, len(S)):
if S[i] == S[i-1]:
return False
return True
def keep_letters(lista, keep):
return filter(lambda x: x in keep, lista)

N = int(raw_input())
S = list(raw_input().strip())
letters = {x: 1 for x in S}
letters = list(combinations(letters.keys(), 2))
#print letters
L = list(S)
first = True
m = 0
for keep in letters:
#print list(S)
lista = keep_letters(list(S), keep)
#print lista
if is_valid(lista):
m = max(m, len(lista))

print m

### Two Characters Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function isAlternating(a){
var alternating = true;
for (var i=0; i<a.length; i++){
if ((i>0) && a[i] == a[i-1]){
alternating = false;
break;
}
}
return alternating;
}
function main() {
var set = new Set();
var arr = s.split('');
var max = 0;
for (let str of arr){
}
set = Array.from(set);
for (var i=0; i<set.length-1; i++){
for (var j=i+1; j<set.length; j++){
var setStay = new Set();
setStay = Array.from(setStay);
var arraynew = arr.slice();
for (let r of set){
if (setStay.indexOf(r) > -1){
continue;
}
arraynew = arraynew.filter(function(element){
return element !== r;
});
}
if (isAlternating(arraynew)){
if (arraynew.length > max){
max = arraynew.length;
}
}
}
}
console.log(max);
}

### Two Characters Solution in Scala

object Solution {
def check(s: String): Boolean = {
(0 until s.length - 1).foreach{i =>
if (s(i) == s(i + 1)) return false
}
true
}

def main(args: Array[String]) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
*/

val letters = s.distinct;
val possible = letters.flatMap{c1 =>
letters.map{c2 =>
if (c1 != c2) {
val s1 = s.filter(c => (c == c1 || c == c2))
val isValid = check(s1)
if (isValid) s1
else ""
}
else {
""
}
}
}
if (possible.filter(x => x != "").isEmpty) println(0)
else {
println(possible.maxBy(_.length).length)
}
}
}

### Two Characters Solution in Pascal

uses math;
var
s:ansistring;
a:array['a'..'z']of longint;
x,y,l:char;
kt:boolean;
kq,i,j,n:longint;
begin
for i:=1 to n do
inc(a[s[i]]);
for x:='a' to 'z' do
for y:=x to 'z' do
if ((x<>y) and (a[x]<>0) and (a[y]<>0)) then
begin
for i:=1 to n do
if (s[i]=x)or(s[i]=y) then
begin
l:=s[i];
break;
end;
kt:=true;
for j:=i+1 to n do
if (s[j]=x)or(s[j]=y) then
begin
if s[j]=l then
begin
kt:=false;
break;
end;
l:=s[j];
end;
if kt=true then kq:=max(kq,a[x]+a[y]);
end;
write(kq);
end.

Disclaimer: This problem (Two Characters) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.