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.

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.

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`.

Example

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.

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

Returns

• 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.

Constraints

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

Sample Input 0

```4
7
RBY_YBR
6
X_Y__X
2
__
6
B_RRBR
```

Sample Output 0

```YES
NO
YES
YES
```

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

```5
5
AABBC
7
AABBC_C
1
_
10
DD__FQ_QQF
6
AABCBC
```

Sample Output 1

```NO
YES
YES
YES
NO
```

### 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 ];

scanf("%d",&Q);
for(int a0 = 0; a0 < Q; a0++){
int n;
scanf("%d",&n);
char* b = (char *)malloc(512000 * sizeof(char));
scanf("%s",b);

min = n+1;
for( i = 0; i<n && b[ i ] != '_'; i++ ){
cont = 0;
if( b[ i ] != '_' ){
j = i+1;
cont++;
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;}
printf("YES\n");

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

///////////////////////////////////////
/// WITHOUT STL

// 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, h[a]);
heapDown(h, 0, a);
}
}

///////////////////////////////////////

bool f() {
char s;
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() {
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;
int n = in.nextInt();
String b = in.next();
for (char c : b.toCharArray()) {
counts[c]++;
}
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";
}
System.out.println(pr);
} else {
String pr = "YES";
for (int i = 0; i < 256; i++) {
if (i != (int)'_' && counts[i]==1)
pr = "NO";
}
System.out.println(pr);
}
}
}
}```

### Happy Ladybugs Solution in Python

```#!/bin/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:
continue
elif key == '_':
continue
else:
balanced = False
if not balanced:
print 'NO'
continue

if '_' not in b:
bounds = []
for char in b:
if bounds == []:
bounds.append([char])
continue
if char == bounds[-1][-1]:
bounds[-1].append(char)
else:
bounds.append([char])
balanced = True

for bound in bounds:
if len(bound) < 2:
balanced = False
break
print 'YES' if balanced else 'NO'
else:
print 'YES'```

### Happy Ladybugs Solution using JavaScript

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

return input_stdin_array[input_currentline++];
}

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

function main() {
for(var a0 = 0; a0 < Q; a0++){
var bugs = {};
var prev = '';
var hasEmptyCells = b.indexOf('_') > -1;
var result = 'YES';

b.forEach(char => {
if (prev && prev === char) {
bugs[char][bugs[char].length-1]++;
} else {
prev = char;
if (!bugs[char]) {
bugs[char] = [];
}
bugs[char].push(1);
}
});

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]
_: 
}
*/
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)) {
println("NO")
}
else {
if (b.contains('_')) {
println("YES")
}
else {
if (checkHappy(b)) println("YES")
else println("NO")
}
}

a0+=1;
}
}
}```

### Happy Ladybugs Solution in Pascal

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

For i:=1 to n do
begin
For j:=0 to 26 do a[j]:=0;
f:=0;

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

if a=0 then
begin
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')
end

else
begin
for j:=0 to 25 do if a[j]=1 then inc(f);
if f>0 then writeln('NO')
else writeln('YES');
end;
end;

End.```

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.

## FAQ:

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.