Happy Ladybugs HackerRank Solution in C, C++, Java, Python

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 ith the 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 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 games of Happy Ladybugs, determine if it’s possible to make all the ladybugs happy. For each game, print YES on a new line if all the ladybugs can be made happy through some number of moves. Otherwise, print NO.

As an example,b=[YYR_B_BR] . You can move the rightmost B and R to make b=[YYRRBB_] and all the ladybugs are happy.

Function Description

Complete the happyLadybugs function in the editor below. It should return an array of strings, either ‘YES’ or ‘NO’, one for each test string.

happyLadybugs has the following parameters:

b: an array of strings that represents the initial positions and colors of the ladybugs

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 describing the n cells of the board.
Constraints

Output Format

For each game, print YES on a new line if it is possible to make all the ladybugs happy. Otherwise, print NO.

Sample Input 0

4
7
RBY_YBR
6
X_Y__X
2
__
6
B_RRBR

Sample Output 0

YES
NO
YES
YES

Happy Ladybugs HackerRank 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,i; 
    scanf("%d",&Q);
    for(int a0 = 0; a0 < Q; a0++){
        int n,a[27]={0},empty=0,f=0,l; 
        scanf("%d",&n);
        char* b = (char *)malloc(512000 * sizeof(char));
        scanf("%s",b);
        for(i=0;i<n;i++)
            {
            if(b[i]!='_')
            a[b[i]-64]++;
            if(b[i]=='_')
                empty++;
        }
        //for(i=1;i<=26;i++)
            //printf("%d ",a[i]);
        for(i=1;i<=26;i++)
                {
                if(a[i]==1)
                    {
                    f=1;
                    break;
                }
            }
        if(f==1)
            printf("NO\n");
        else if(empty==0)
        {
            f=0;
            for(i=1;i<n-1;i++)
                {
                if(b[i]!=b[i-1] && b[i]!=b[i+1])
                    {
                    f=1;
                    break;
                }
            }
            if(f==1)
            printf("NO\n");
            else
            printf("YES\n");
        }
        else
            printf("YES\n");
    }
    return 0;
}

 

Happy Ladybugs HackerRank Solution in C++

#include <stdio.h>

int cnt[26];

int main(){
    int g;
    scanf("%d", &g);
    for(int test=0; test<g; test++){
        int n;
        char s[105];
        scanf("%d", &n);
        scanf("%s", &s[1]);
        s[0] = '.';
        int fr=0;
        int valid=1;
        for(int i=0; i<26; i++) cnt[i] = 0;
        for(int i=1; s[i]; i++) cnt[s[i]-'A']++;
        for(int i=0; i<26; i++) if(cnt[i] == 1) valid = 0;
        for(int i=1; s[i]; i++) if(s[i] == '_') fr=1;
        if(!valid){ printf("NO\n"); continue; }
        if(fr){ printf("YES\n"); continue; }
        for(int i=1; s[i]; i++){
            if(s[i] != s[i-1] && s[i] != s[i+1]) valid = 0;
        }
        if(valid) printf("YES\n");
        else printf("NO\n");
        
    }
}

 

Happy Ladybugs HackerRank 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);
            }
        }
    }
}

 

Happy Ladybugs HackerRank 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 HackerRank Solution in C#

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('_'))
            {
                int[] counts = new int[26];
                foreach(char c in b)
                {
                    if (c != '_') counts[(int)(c - 'A')]++;
                }
                foreach(int c in counts)
                {
                    if (c == 1)
                    {
                        happy = false;
                        break;
                    }
                }
            }else
            {
                for(int i=0;i<n;i++)
                {
                    if (b[i] != '_')
                    {
                        bool friendleft = i > 0 && b[i - 1] == b[i];
                        bool friendright = i < n - 1 && b[i + 1] == b[i];
                        if (!friendleft && !friendright)
                        {
                            happy = false;
                            break;
                        }
                    }
                }
            }
            Console.WriteLine(happy ? "YES" : "NO");
        }
    }
}

 

Attempt Happy Ladybugs HackerRank Challenge

Link –¬†https://www.hackerrank.com/challenges/happy-ladybugs/

Next HackerRank Challenge Solution 

Link –¬†https://exploringbits.com/strange-counter-hackerrank-solution/

Leave a Comment