Skip to content
Programmingoneonone
Programmingoneonone
  • Home
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerRank Two Characters problem solution

YASH PAL, 31 July 202422 January 2026

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

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.

HackerRank Two Characters problem solution

HackerRank Two Characters problem solution in Python.

#!/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)

Two Characters problem solution in Java.

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

Two Characters problem solution in C++.

#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("%dn", 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);
}

Algorithms coding problems solutions AlgorithmsHackerRank

Post navigation

Previous post
Next post

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you a student and stuck with your career or worried about real-time things, and don't know how to manage your learning phase? Which profession to choose? and how to learn new things according to your goal, and land a dream job. Then this might help to you.

Hi My name is YASH PAL, founder of this Blog and a Senior Software engineer with 5+ years of Industry experience. I personally helped 40+ students to make a clear goal in their professional lives. Just book a one-on-one personal call with me for 30 minutes for 300 Rupees. Ask all your doubts and questions related to your career to set a clear roadmap for your professional life.

Book session - https://wa.me/qr/JQ2LAS7AASE2M1

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes