Two Characters

Problem Statement :

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.


s = 'abcacdabd'

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


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.


1  <=  length of s  <=  1000

Solution :


                            Solution in C :

In  C++  :

#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;
    string 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)
        if (valid(x))
            ans = max(ans, (int)x.size());
    printf("%d\n", ans);

In   Java  :

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(;
        int n = in.nextInt();
        String str =;
        HashSet<Character> set = new HashSet<Character>();
        char[] ar = str.toCharArray();
        for (char c : ar) set.add(c);
        int ans = 0;
        Character[] keys = set.toArray(new Character[set.size()]);
        for (int i = 0 ; i < set.size() ; i++) {
            for (int j = i+1 ; j < set.size() ; j++) {
                String b = str;
                for (char c : set) {
                    if (c != keys[i] && c != keys[j]) b = b.replace(c + "", "");
                char[] ts = b.toCharArray();
                boolean valid = ts.length > 0;
                for (int k = 0 ; valid && k < ts.length - 1 ; k++) {
                    if (ts[k] == ts[k+1]) valid = false; 
                if (valid) ans = Math.max(ans, ts.length);

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, you[26] = { 0 }, c = 0, i, j, k, bv = 0, stat;
	scanf("%d", &len);
	char s[1010];
	scanf("%s", s);
	for (i = 0; i < len; i++)you[s[i] = s[i] - 'a']++;
	for (i = 0; i < 26; i++)if (you[i])c++;
	if (c <= 1) {
		return 0;
	for (i = 0; i < 26; i++)for (j = i + 1; j < 26; j++)if (you[i] && you[j]) {
		stat = -1;
		c = 0;
		for (k = 0; k < len; k++)if (s[k] == i || s[k] == j) {
			if (stat == -1)stat = (s[k] == j);
			else if (stat == (s[k] == j))goto nxt;
			else stat = 1 - stat;
		if (c > bv)bv = c;
	printf("%d\n", bv);
	return 0;

In   Python3  :

def char_range(c1, c2):
    for c in range(ord(c1), ord(c2)+1):
        yield chr(c)
def is_alternating(s):
    for i in range(len(s) - 1):
        if s[i] == s[i+1]:
            return False
    return True
len_s = int(input())

s = input()

max_len = 0
for c1 in char_range('a', 'z'):
    for c2 in char_range('a', 'z'):
        if c1 == c2:
        new_string = [c for c in s if c == c1 or c == c2]
        new_string_len = len(new_string)
        if is_alternating(new_string) and new_string_len > 1:
            if new_string_len > max_len:
                max_len = new_string_len

View More Similar Problems

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →