Skip to content
Programmingoneonone
Programmingoneonone
  • Engineering Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
    • 100+ C++ Programs
  • Solutions
    • HackerRank
      • Algorithms Solutions
      • C solutions
      • C++ solutions
      • Java solutions
      • Python solutions
    • Leetcode Solutions
    • HackerEarth Solutions
  • Work with US
Programmingoneonone
Programmingoneonone

HackerRank Alternating Characters problem solution

YASH PAL, 31 July 20246 February 2026

In this HackerRank Alternating Characters Interview preparation kit problem solution, You are given a string containing characters A and B only. Your task is to change it into a string such that there are no matching adjacent characters. To do this, you are allowed to delete zero or more characters in the string.

Your task is to find the minimum number of required deletions.

Function Description

Complete the alternatingCharacters function in the editor below.

alternatingCharacters has the following parameter(s):

  • string s: a string

Returns

  • int: the minimum number of deletions required
HackerRank Alternating Characters Interview preparation kit solution

HackerRank Alternating Characters problem solution in Python.

def f(s):
    return sum(1 for c1, c2 in zip(s, s[1:]) if c1 == c2)

t = int(input())
for _ in range(t):
    print(f(input()))

Alternating Characters problem solution in Java.

import java.io.*;
import java.util.*;
import java.math.*;


public class Solution {
	static BufferedReader in;
	static PrintWriter out;
	static StringTokenizer tok;
	
	
	static void solve() throws Exception {
		int t = nextInt();
		for (int tt = 0; tt < t; ++tt) {
			String s = next();
			int res = 0;
			for (int i = 0; i < s.length(); ++i) {
				if (i - 1 >= 0 && s.charAt(i - 1) == s.charAt(i)) {
					++res;
				}
			}
			out.println(res);
		}
	}

	static int sqr(int x) {
		return x*x;
	}
	
	static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}

	static long nextLong() throws IOException {
		return Long.parseLong(next());
	}

	static double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}

	static BigInteger nextBigInteger() throws IOException {
		return new BigInteger(next());
	}
	
	static String next() throws IOException {
		while (tok == null || !tok.hasMoreTokens()) {
			tok = new StringTokenizer(in.readLine());
		}
		return tok.nextToken();
	}
	
	static String nextLine() throws IOException {
		tok = new StringTokenizer("");
		return in.readLine();
	}

	static boolean hasNext() throws IOException {
		while (tok == null || !tok.hasMoreTokens()) {
			String s = in.readLine();
			if (s == null) {
				return false;
			}
			tok = new StringTokenizer(s);
		}
		return true;
	}

	public static void main(String args[]) {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(new OutputStreamWriter(System.out));
			//in = new BufferedReader(new FileReader("input.in"));
			//out = new PrintWriter(new FileWriter("output.out"));
			solve();
			in.close();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			java.lang.System.exit(1);
		}
	}
}

Problem solution in C++ programming.

#include <iostream>
#include <string>

using namespace std ;

int main()
{
    int test_cases;
    cin >> test_cases ;
    string str;
    int count  ;
    int j ;
    char prev ;
    for ( int i =0 ; i < test_cases ;i++)
    {
        cin >> str ;
        j = 1; prev = str[0]; count = 0 ; 
        while((int)str[j]!=0)
        {
            if(str[j] == prev)
                count ++ ;
            else
                prev = str[j] ;
            j++ ;
        }
        cout << count << endl ;
    }
    return 0 ;
}

Problem solution in C programming.

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

int main() 
{
    int t;
    long i=0;
    unsigned int count=0;
    char * c;
    scanf("%d",&t);
    c=(char *)malloc(sizeof(char)*(100002));
    while(t--)
    {
        scanf("%s",c);
        for(i=0; *(c+i); i++)
        {
            if(c[i]==c[i+1])
            {
                count++;
            }
        }
        printf("%un",count);
        count=0;
    }
      
    return 0;
}

Problem solution in JavaScript programming.

function processData(input) {
  var inputArray = input.split('n');
  var t = parseInt(inputArray[0]);
  var pointer = 1;
  while (pointer <= t) {
    var target = inputArray[pointer];
    var count = 0;
    for (var i=1; i<target.length; i++) {
      if (target[i] == target[i-1]) {
        count += 1;
      }
    }
    console.log(count);
    pointer += 1;
  }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

coding problems solutions Hackerrank Problems Solutions interview prepration kit HackerRank

Post navigation

Previous post
Next post

Programmingoneonone

We at Programmingoneonone, also known as Programming101 is a learning hub of programming and other related stuff. We provide free learning tutorials/articles related to programming and other technical stuff to people who are eager to learn about it.

Pages

  • About US
  • Contact US
  • Privacy Policy

Practice

  • Java
  • C++
  • C

Follow US

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