HackerRank Happy Ladybugs Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Happy Ladybugs Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

Happy Ladybugs Solution
Happy Ladybugs Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Happy Ladybugs


Happy Ladybugs is a board game having the following properties:

  • The board is represented by a string, b, of length n. The ith character of the string, b[i], denotes the ith cell of the board.
    • If b[i] is an underscore (i.e._), it means the  cell of the board is empty.
    • If b[i] is an uppercase English alphabetic letter (ascii[AZ]), it means the ith cell contains a ladybug of color b[i].
    • String b will not contain any other characters.
  • A ladybug is happy only when its left or right adjacent cell (i.e., b[i+1]) is occupied by another ladybug having the same color.
  • In a single move, you can move a ladybug from its current position to any empty cell.

Given the values of n and b for g games of Happy Ladybugs, determine if it’s possible to make all the ladybugs happy. For each game, return YES if all the ladybugs can be made happy through some number of moves. Otherwise, return NO.


b = [Y Y R_B_BR]

You can move the rightmost B and R to make b = [YYRRBB . . . ] and all the ladybugs are happy. Return YES.

Function Description

Complete the happyLadybugs function in the editor below.

happyLadybugs has the following parameters:

  • string b: the initial positions and colors of the ladybugs


  • string: either YES or NO

Input Format

The first line contains an integer g, the number of games.

The next g pairs of lines are in the following format:

  • The first line contains an integer n, the number of cells on the board.
  • The second line contains a string b that describes the n cells of the board.


  • 1 <= gn <= 100
  • b[i] ∈ {ascii[A – Z]}

Sample Input 0


Sample Output 0


Explanation 0

The four games of Happy Ladybugs are explained below:

  1. Initial board:
    After the first move:
    After the second move:
    After the third move:

Now all the ladybugs are happy, so we print YES on a new line.

  1. Initial board: Now all the ladybugs are happy, so we print YES on a new line.
  2. There is no way to make the ladybug having color Y happy, so we print NO on a new line.
  3. There are no unhappy ladybugs, so we print YES on a new line.
  4. Move the rightmost B and R to form b = [BBRRR . . . ].

Sample Input 1


Sample Output 1


HackerRank Happy Ladybugs Solution

Happy Ladybugs Solution 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 Q; 
    int ban = 0, i, j, cont, min;
    int C[ 29 ];
    for(int a0 = 0; a0 < Q; a0++){
        int n; 
        char* b = (char *)malloc(512000 * sizeof(char));
        min = n+1;
        for( i = 0; i<n && b[ i ] != '_'; i++ ){
             cont = 0;
            if( b[ i ] != '_' ){
              j = i+1;
              while( b[ j ] == b[ i ] ){ cont++; j++; }
              i = j-1;
              min = (min > cont )?cont:min;
        if( min == 1 && i == n ){ printf("NO\n"); continue; }
        for( i = 0; i<28; i++ ) C[ i ] = 0;
        for( i = 0; i<n; i++ ) C[ b[ i ] - 'A']++;
        for( i = 0; i<28 && C[ i ] != 1; i++ ) ;
        if( i < 28 ){ printf("NO\n"); continue;}
    return 0;

Happy Ladybugs Solution in Cpp

#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <set>
#include <algorithm>
using namespace std;

#define REP(i, n) for (int i=0, ___=(n); i<___; ++i)
#define FOR(i, a, b) for (int i=(a), ___=(b); i<=___; ++i)
#define FORD(i, a, b) for (int i=(a), ___=(b); i>=___; --i)

int read() { int n; scanf("%d", &n); return n; }
long long readl() { long long n; scanf("%lld", &n); return n; }
double readd() { double d; scanf("%lf", &d); return d; }


// kopiec

#define HeapT int
#define heapLeft(i) (2*(i)+1)
#define heapRight(i) (2*(i)+2)
#define heapParent(i) (((i)-1)/2)

inline void swap(HeapT &a, HeapT &b) {
	HeapT t = a; a = b; b = t;

inline void heapDown(HeapT *h, int a, int n) {
	while (heapLeft(a) < n) {
		int b = heapLeft(a);
		if (b+1 < n && h[b+1] > h[b]) b++;
		if (h[b] <= h[a]) break;
		swap(h[a], h[b]);
		a = b;

inline void heapUp(HeapT *h, int a) {
	while (a > 0) {
		int b = heapParent(a);
		if (h[a] > h[b]) {
			swap(h[a], h[b]);
			a = b;

void heapMake(HeapT *h, int n) {
	for (int a=heapParent(n-1); a>=0; --a)
		heapDown(h, a, n);

void heapSort(HeapT *h, int n) {
	heapMake(h, n);
	for (int a=n-1; a>0; --a) {
		swap(h[0], h[a]);
		heapDown(h, 0, a);


bool f() {
	int n = read();
	char s[111];
	scanf("%s", s);
	map<char, int> m;
	REP(i, n) m[s[i]]++;
	if (m.count('_') > 0) {
		FOR(c, 'A', 'Z') if (m[c] == 1) return false;
		return true;
	REP(i, n) {
		bool ok = false;
		if (i-1 >= 0 && s[i-1] == s[i]) ok = true;
		if (s[i+1] == s[i]) ok = true;
		if (!ok) return false;
	return true;

int main() {
	int t = read();
	while (t--) {
		printf("%s\n", f() ? "YES" : "NO");
	return 0;

Happy Ladybugs Solution in Java

import java.io.*;
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(System.in);
        int Q = in.nextInt();
        for(int a0 = 0; a0 < Q; a0++){
            char[] counts = new char[256];
            int n = in.nextInt();
            String b = in.next();
            for (char c : b.toCharArray()) {
            if (counts['_']==0) {
                String pr = "YES";
                for (int i = 0; i < n; i++) {
                    if ((i==0||b.charAt(i)!=b.charAt(i-1))&&(i==n-1||b.charAt(i)!=b.charAt(i+1)))
                        pr = "NO";
            } else {
                String pr = "YES";
                for (int i = 0; i < 256; i++) {
                    if (i != (int)'_' && counts[i]==1)
                        pr = "NO";

Happy Ladybugs Solution in Python


import sys
from collections import Counter
from string import ascii_uppercase

Q = int(raw_input().strip())
for a0 in xrange(Q):
    n = int(raw_input().strip())
    b = raw_input().strip()

    c = Counter(b)
    balanced = True
    for key, value in c.iteritems():
        if key in ascii_uppercase and value > 1:
        elif key == '_':
            balanced = False
    if not balanced:
        print 'NO'
    if '_' not in b:
        bounds = []
        for char in b:
            if bounds == []:
            if char == bounds[-1][-1]:
        balanced = True
        for bound in bounds:
            if len(bound) < 2:
                balanced = False
        print 'YES' if balanced else 'NO'
        print 'YES'

Happy Ladybugs Solution using JavaScript


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

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

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

function main() {
    var Q = parseInt(readLine());
    for(var a0 = 0; a0 < Q; a0++){
        var n = parseInt(readLine());
        var bugs = {};
        var prev = '';
        var b = readLine().split('');
        var hasEmptyCells = b.indexOf('_') > -1;
        var result = 'YES';
        b.forEach(char => {
            if (prev && prev === char) {
            } else {
                prev = char;
                if (!bugs[char]) {
                    bugs[char] = [];
        delete bugs['_'];
        Object.keys(bugs).forEach(bugColor => {
            let total = bugs[bugColor].reduce((prev, curr) => prev + curr, 0);
            let hasUnhappyBugs = bugs[bugColor].filter(x => x === 1).length > 0;
            if ((total === 1) || (hasUnhappyBugs && !hasEmptyCells)) {
                result = 'NO';
        R: [1, 1]
        B: [1, 1]
        Y: [1, 1]
        _: [1]
        process.stdout.write(result + '\n');

Happy Ladybugs Solution in Scala

object Solution {

    def checkHappy(s: String) = {
        if (s(0) != s(1)) false
        else {
            val n = s.length - 1
            if (s(n) != s(n - 1)) false
            else (1 until n).map(i => s(i) == s(i - 1) || s(i) == s(i + 1)).forall(_ == true)
    def main(args: Array[String]) {
        val sc = new java.util.Scanner (System.in);
        var Q = sc.nextInt();
        var a0 = 0;
        while(a0 < Q){
            var n = sc.nextInt();
            var b = sc.next();
            val colors = b.toSet;
            val nums = colors.filter(_ != '_').map(c => b.count(_ == c))
            if (nums.exists(_ == 1)) {
            else {
                if (b.contains('_')) {
                else {
                    if (checkHappy(b)) println("YES")
                    else println("NO")

Happy Ladybugs Solution in Pascal

s:string; a:array[0..26] of byte; n,f,l,i,j:byte;

For i:=1 to n do
    For j:=0 to 26 do a[j]:=0;
    For j:=1 to l do
        if s[j]='_' then inc(a[26])
        else inc(a[ord(s[j])-ord('A')]);

    if a[26]=0 then
        for j:=1 to l do if (s[j]=s[j+1]) or (s[j]=s[j-1]) then inc(f);
        if f=l then writeln('YES')
        else writeln('NO')
          for j:=0 to 25 do if a[j]=1 then inc(f);
          if f>0 then writeln('NO')
          else writeln('YES');


Disclaimer: This problem (Happy Ladybugs) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment