HackerRank Happy Ladybugs Problem Solution Yashwant Parihar, April 19, 2023April 19, 2023 In this post, we will solve HackerRank Happy Ladybugs Problem Solution. 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 ¿th cell of the board.If b[i] is an underscore (i.e., _), it means the ith cell of the board is empty.If b[i] is an uppercase English alphabetic letter (ascii[A-Z]), it means the ¿th 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.Exampleb = [YYR_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 or NO Input FormatThe 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 then cells of the board. 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: 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 print NO 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 Problem Solution Happy Ladybugs C Solution #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> char arr[101]; int compare (const void * a, const void * b) { return ( *(char*)a - *(char*)b ); } int main(){ int G,N,whitespaces,i,unhappy; scanf("%d",&G); while(G--) { unhappy=0; whitespaces=0; scanf("%d\n",&N); i=N; while(i--) { scanf("%c",&arr[N-i-1]); if(arr[N-i-1] == '_') whitespaces++; } if(whitespaces > 0) qsort(arr,N,sizeof(char), compare); //for(i=0;i<N;i++) // printf("%c",arr[i]); //printf("\n"); for(i = 0; i<N && !unhappy; i++) { if (arr[i] != '_' && ( (i==0 && i+1<N && arr[i+1] != arr[i]) || (i==N-1 && i-1>=0 && arr[i-1] != arr[i]) || (arr[i]!=arr[i-1] && arr[i]!=arr[i+1]))) unhappy++; } if(unhappy) printf("NO\n"); else printf("YES\n"); } return 0; } Happy Ladybugs C++ Solution #include <iostream> #include <vector> #include <algorithm> #include <string> #include <ctype.h> #include <deque> #include <queue> #include <cstring> #include <set> #include <list> #include <map> #include <random> #include <unordered_map> #include <stdio.h> using namespace std; typedef long long ll; typedef std::vector<int> vi; typedef std::vector<bool> vb; typedef std::vector<string> vs; typedef std::vector<double> vd; typedef std::vector<long long> vll; typedef std::vector<std::vector<int> > vvi; typedef vector<vvi> vvvi; typedef vector<vll> vvll; typedef std::vector<std::pair<int, int> > vpi; typedef vector<vpi> vvpi; typedef std::pair<int, int> pi; typedef std::pair<ll, ll> pll; typedef std::vector<pll> vpll; const long long mod = 1000000007; #define all(c) (c).begin(),(c).end() #define sz(c) (int)(c).size() #define forn(i, a, b) for(int i = a; i < b; i++) #define pb push_back #define mp make_pair int main() { int t; scanf("%d\n", &t); forn(agag,0,t) { int n; scanf("%d\n", &n); string s; getline(cin, s); int cem =0; vi cnt(26,0); forn(i,0,n) { if(s[i] == '_') cem++; else cnt[s[i]-'A']++; } if(cem==0) { string ans = "YES"; forn(i,0,n) { bool f= false; if(i<n-1 && s[i+1]==s[i]) f = true; if(i>0 && s[i-1]==s[i]) f = true; if(!f) ans = "NO"; } cout<<ans<<endl; } else { string ans = "YES"; forn(i,0,26) if(cnt[i] == 1) ans = "NO"; cout<<ans<<endl; } } } Happy Ladybugs C Sharp Solution using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { int Q = Convert.ToInt32(Console.ReadLine()); for (int a0 = 0; a0 < Q; a0++) { int n = Convert.ToInt32(Console.ReadLine()); string b = Console.ReadLine(); bool happy = true; if (!b.Contains("_")) { for(int i = 0; i < b.Length; i++) { char left; if (i > 0) left = b[i - 1]; else left = '_'; char right; if (i < b.Length-1) right = b[i + 1]; else right = '_'; if (b[i] != left && b[i] != right) { happy = false; break; } } } else { Dictionary<char, int> dict = new Dictionary<char, int>(); foreach (char c in b) { if (c != '_') { if (dict.ContainsKey(c)) { dict[c] = dict[c] + 1; } else { dict.Add(c, 1); } } } foreach (KeyValuePair<char, int> pair in dict) { if (pair.Value < 2) { happy = false; break; } } } Console.WriteLine(happy ? "YES" : "NO"); } } } Happy Ladybugs Java Solution import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; class Result { /* * Complete the 'happyLadybugs' function below. * * The function is expected to return a STRING. * The function accepts STRING b as parameter. */ public static String happyLadybugs(String b) { // Write your code here int [] cnts = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; for (int i = 0; i < b.length(); i++) { if (b.charAt(i) != '_') cnts[b.charAt(i) - 'A']++; } boolean byes = true; for (int i = 0; i < cnts.length; i++) { if (cnts[i] == 1) { byes = false; break; } } if (byes) { if (b.indexOf("_") >= 0) { return "YES"; } else { for (int i = 0; i < b.length(); i++) { if (i == 0) { if (b.charAt(i) != b.charAt(i+1)) { return "NO"; } } else if (i == b.length() - 1) { if (b.charAt(i) != b.charAt(i-1)) { return "NO"; } } else { if (b.charAt(i) != b.charAt(i-1) && b.charAt(i) != b.charAt(i+1)) { return "NO"; } } } return "YES"; } } else { return "NO"; } } } public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int g = Integer.parseInt(bufferedReader.readLine().trim()); IntStream.range(0, g).forEach(gItr -> { try { int n = Integer.parseInt(bufferedReader.readLine().trim()); String b = bufferedReader.readLine(); String result = Result.happyLadybugs(b); bufferedWriter.write(result); bufferedWriter.newLine(); } catch (IOException ex) { throw new RuntimeException(ex); } }); bufferedReader.close(); bufferedWriter.close(); } } Happy Ladybugs JavaScript Solution 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 b = readLine(); var result = null; if(b.includes('_')){ var ladybugs = {}; for(var i = 0; i < n; i++){ var ladybug = b[i]; if(ladybug != '_'){ ladybugs[ladybug] = ladybugs[ladybug] + 1 || 1; } } result = Object.keys(ladybugs).reduce(function(x,y){ return x && ladybugs[y] > 1; }, true); } else{ result = b.split('').reduce(function(total, value, index){ return total && (value == b[index-1] || value == b[index + 1]); }, true); } console.log(result ? 'YES' : 'NO'); } } Happy Ladybugs Python Solution #!/bin/python3 import sys from collections import Counter Q = int(input().strip()) for a0 in range(Q): n = int(input().strip()) b = input().strip() myList = list(b) d = Counter(myList) if len(d) < 2: if d["_"] == 0: for k in d: if d[k] > 1: print("YES") else: print("NO") else: print("YES") if len(d)>=2: if d["_"] == 0: count = 1 for k in range(1, n): if myList[k] == myList[k-1]: count+=1 else: if count==1: print("NO") break else: count = 1 if k == n-1 and count==1: print("NO") elif k == n-1 and count!=1: print("YES") else: c = False for x in d: if d[x]==1 and x!="_": c = True print ("NO") break if c == False: print("YES") Other Solutions HackerRank Strange Counter Problem Solution HackerRank 3D Surface Area Problem Solution c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython