In this HackerRank Two Characters problem, 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.

HackerRank Two Characters problem solution


Problem solution in Python programming.

#!/bin/python3

import sys

def valid(s):
    if len(s) <= 1:
        return False
    if s[0] == s[1]:
        return False
    if len(set(s)) > 2:
        return False
    for i in range(2, len(s)):
        if i%2 == 0:
            if s[i] != s[0]:
                return False
        else:
            if s[i] != s[1]:
                return False
    return True
    

n = int(input().strip())
s = input().strip()

r = 0
alp = 'abcdefghijklmnopqrstuvwxyz'
for k in alp:
    for l in alp:
        if k >= l:
            continue
        f = list(filter(lambda x: x == k or x == l, s))
        if valid(f):
            r = max(r, len(f))
print(r)


Problem solution in Java Programming.

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

public class Solution {
    static boolean isAlt(int[] str){
        return str[0]!=str[1] && IntStream.range(2,str.length).allMatch(i->str[i]==str[i%2]);
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int len = in.nextInt();
        String s = in.next();
        int[] nums=s.chars().distinct().toArray();
        int maxLength=0;
        for(int i=0; i<nums.length; i++){
            for(int j=i+1; j<nums.length; j++){
                int a=nums[i]; int b=nums[j];
                int [] removed=s.chars().filter(c->c==a||c==b).toArray();
                if(isAlt(removed) && removed.length>maxLength)
                    maxLength=removed.length;
            }
        }
        System.out.println(maxLength);
            
    }
}


Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

bool alternating(string &s) {
    if (s.size() < 2) return 0;
    char a = s[0];
    char b = s[1];
    if (a == b) return 0;
    
    for (int i=2; i<s.size(); i++) {
        if (i & 1) {
            if (s[i] != b) return 0;
        } else if (s[i] != a) return 0;
    }
    
    return 1;
}

int main() {
    string s;
    cin >> s;
    cin >> s;
    
    int ans = 0;
    for (char a = 'a'; a <= 'z'; a++) {
        for (char b = 'a'; b <= 'z'; b++) {
            if (a == b) continue;
            string t;
            for (int i=0; i<s.size(); i++) {
                if (s[i] == a || s[i] == b) t += s[i];
            }
            
            if (alternating(t)) ans = max(ans, (int) t.size());
        }
    }
    cout << ans << endl;
    return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <stdlib.h>

int alternating_length(char *s, char x, char y) {
    int len = 0, which = 0;
    for (int i = 0; s[i]; i++) {
        if (s[i] == x) {
            if (which == 0) {
                len++;
                which = 1;
            } else {
                return 0;
            }
        } else if (s[i] == y) {
            if (which == 1) {
                len++;
                which = 0;
            } else {
                return 0;
            }
        }
    }
    return len;
}

int main(void) {
    int n;
    scanf("%d", &n);
    char s[1002];
    scanf("%s", s);
    int maxLen = 0;
    for (char x = 'a'; x <= 'z'; x++) {
        for (char y = 'a'; y <= 'z'; y++) {
            if (x == y) continue;
            int len = alternating_length(s, x, y);
            if (len > maxLen) maxLen = len;
        }
    }
    if (maxLen == 1) maxLen = 0;
    printf("%d\n", maxLen);
    return 0;
}


Problem solution in JavaScript programming.

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();    
});

function readLine() {
    return input_stdin_array[input_currentline++];
}

/////////////// ignore above this line ////////////////////

function main() {
    var len = parseInt(readLine());
    var s = readLine();
    var m = {};
    for (let i = 0, len = s.length; i < len; i++) {
        m[s[i]] ? m[s[i]]++ : m[s[i]] = 1;
    }
    const sorted = Object.keys(m).sort((a, b) => m[a] > m[b]);
    let pairs = [];
    for (let i = 0, len = sorted.length; i < len; i++) {
        for (let j = i + 1; j < len; j++) {
            Math.abs(m[sorted[i]] - m[sorted[j]]) <= 1 ? pairs.push([sorted[i], sorted[j]]) : null;
        }
    }
    let maxCount = 0;
    pairs.some(pair => {
        let isFirst = null;
        let count = 0;
        for (let i = 0, len = s.length; i < len; i++) {
            if (s[i] === pair[0]) {
                if (isFirst == null || !isFirst) {
                    isFirst = true;
                    count++;
                } else {
                    break;
                }
            }
            else if (s[i] === pair[1]) {
                if (isFirst == null || isFirst) {
                    isFirst = false;
                    count++;
                } else {
                    break;
                }
            }
            if (i === s.length - 1 && count > maxCount) {
                maxCount = count;
            }
        }
    });
    console.log(maxCount);
}