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.

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 Structures, RDBMS Programs, Java Programs Solutions, Fiverr Skills Test answers, Google Course Answers, Linkedin Assessment, and Coursera Quiz Answers.
HackerRank Happy Ladybugs
Task
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.
- 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.
happyLadybugs has the following parameters:
- string b: the initial positions and colors of the ladybugs
Returns
- string: either
YES
orNO
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 <= g, n <= 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:
- 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.
- Initial board: Now all the ladybugs are happy, so we print
YES
on a new line. - There is no way to make the ladybug having color
Y
happy, so we printNO
on a new line. - There are no unhappy ladybugs, so we print
YES
on a new line. - 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
HackerRank Happy Ladybugs Solution
HackerRank 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; }
HackerRank 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[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; }
HackerRank 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()) { 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); } } } }
HackerRank 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'
HackerRank 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(); }); 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) { 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] _: [1] } */ process.stdout.write(result + '\n'); } }
HackerRank 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; } } }
HackerRank Happy Ladybugs Solution in Pascal
Var s:string; a:array[0..26] of byte; n,f,l,i,j:byte; Begin Readln(n); For i:=1 to n do begin For j:=0 to 26 do a[j]:=0; f:=0; readln(l); readln(s); For j:=1 to l do begin if s[j]='_' then inc(a[26]) else inc(a[ord(s[j])-ord('A')]); end; if a[26]=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.