Two Characters HackerRank Solution

In this Two Characters HackerRank solution,  we have Given a string and we need remove characters until the string is made up of any two alternating characters. When we choose a character to remove, all instances of that character must be removed. Also we need to Determine the longest string possible that contains just two alternating letters.

Two Characters Problem HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

Problem Solution in Python

def alternate(s):
    characters = sorted(list(set(s)))
    pairs = []
    for i in range(len(characters)):
        for j in range(i + 1, len(characters)):
            pairs.append([characters[i], characters[j]])
   
    newSlen = 0
    for p in pairs:
        newS = []
        for c in s:
            if c in p:
                newS.append(c)
               
        valid = 1
        for i in range(1, len(newS)):
            if newS[i] == newS[i-1]:
                valid = 0
                break
       
        if valid and len(newS) > newSlen:
            newSlen = len(newS)
           
    return newSlen

Problem Solution in C#

public static int alternate(string s)
    {
        char[] chars = s.ToCharArray();
        char[] distinct = chars.Distinct().ToArray();
        int l = distinct.Length;
        int n = 0;
       
        for (int i = 0; i < l - 1; i++) {
            for (int j = i + 1; j < l; j++) {
                char c1 = distinct[i];
                char c2 = distinct[j];
                int count = 0;
                char prev = (char)1;
                foreach (char c in s) {
                    if (c != c1 && c != c2) {
                        // go to next
                    } else if (prev != c) {
                        // char alternates / first in list
                        prev = c;
                        count++;
                    } else if (prev == c) {
                        // char repeats
                        count = 0;
                        break;
                    }
                }
                n = Math.Max(count, n);
            }
        }
        return n;
    }

Problem Solution in C++

int alternate(string s, ofstream& fout)
{
    if(s.size() == 0 || s.size() == 1)
    {
        return 0;
    }


    string makeUnique = s;    
    makeUnique.erase(unique(makeUnique.begin(), makeUnique.end()), makeUnique.end());
   
    vector<char> charsVec;
    for(const auto& character : makeUnique)
    {
        charsVec.push_back(character);
    }
   
    int maxString = 0;
    for(int i = 0; i < charsVec.size(); i++)
    {
        char unique1 = charsVec[i];
        for(int j = 0; j < charsVec.size(); j++)
        {
            char unique2 = charsVec[j];
           
            string temp = "";
            for(int k = 0; k < s.size(); k++)
            {
                if(s[k] == unique1 || s[k] == unique2)
                {
                    temp += s[k];
                }
            }
           
            string toCheck1{unique1, unique1};
            string toCheck2{unique2, unique2};
           
            if(temp.find(toCheck1) == string::npos &&
                temp.find(toCheck2) == string::npos)
            {
                maxString = max(maxString, static_cast<int>(temp.size()));
            }
        }
    }
   
    return maxString;
}

Problem Solution in JavaScript

function alternate(s) {
    let r = []
    const ss = [...new Set(s)]
    while (ss.length) {
        let x = ss.shift()
        for (const y of ss) {
            const del = s.replace(new RegExp('[^'+x+y+']', 'g'), '')
            if (!/([a-z])\1/.test(del)) r.push(del)
        }
    }
    console.log(r)
    return Math.max(0, ...(r.map(e => e.length)))
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems

Leave a Comment