HackerRank Game of Thrones I Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Game of Thrones I 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.

Game of Thrones I problem solution
Game of Thrones I problem 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 Game of Thrones I

Task

Dothraki are planning an attack to usurp King Roberts throne. King Robert learns of this conspiracy from Raven and plans to lock the single door through which the enemy can enter his kingdom.

door

But, to lock the door he needs a key that is an anagram of a palindrome. He starts to go through his box of strings, checking to see if they can be rearranged into a palindrome. Given a string, determine if it can be rearranged into a palindrome. Return the string YES or NO.

Example

s = “aabbccdd”

One way this can be arranged into a palindrome is abcddcba. Return YES.

Function Description

Complete the gameOfThrones function below.

gameOfThrones has the following parameter(s):

  • string s: a string to analyze

Returns

  • string: either YES or NO

Input Format

A single line which contains s.

Constraints

  • 1 <= |s| <= 105
  • s contains only lowercase letters in the range ascii[a . . . z]

Sample Input 0

aaabbbb

Sample Output 0

YES

Explanation 0

A palindromic permutation of the given string is bbaaabb.

Sample Input 1

cdefghmnopqrstuvw

Sample Output 1

NO

Explanation 1

Palindromes longer than 1 character are made up of pairs of characters. There are none here.

Sample Input 2

cdcdcdcdeeeef

Sample Output 2

YES

Explanation 2

An example palindrome from the string: ddcceefeeccdd.

HackerRank Game of Thrones I Solution

Game of Thrones I Solution in C

#include<stdio.h>

int main()
{
	int a[26],i,tp;
	char c;
	for (i=0;i<26;i++)
	a[i]=0;
	while ((c=getchar())!=EOF&&c!='\n')
	{
		a[c-97]++;
	}
	tp=1;
	for (i=0;i<26;i++)
	{
		if (a[i]%2!=0&&tp==1)
		tp=0;
		else if (a[i]%2!=0&&tp==0)
		{
			printf("NO");
			break;
		}
	}
	if (i==26)
	printf("YES");
	return 0;
}

Game of Thrones I Solution in Cpp

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <string.h>
#include <vector>
#include <set>
#include <queue>
#include <math.h>
#include <map>
#include <stdlib.h>
using namespace std;
#define ACCEPTED 0
#define F first
#define S second
#define PI (acos(-1.0))
#define EPS (1e-11)
#define INF (1<<30)
int dx[] = {1,0,-1,0}, dy[] = {0,1,0,-1};
/* ============================================== */

int main(){
  string s;
  cin >>  s;

  vector<int> v(256, 0);
  for(int i=0; i<s.size(); i++) v[s[i]]++;

  int impar =0;
  for(int i=0; i<256; i++)
    if(v[i]%2) impar++;

  if((s.size()%2 == 0 && impar == 0) || (s.size()%2==1 && impar == 1))
    puts("YES");
  else puts("NO");
  
  return ACCEPTED;
}
/* ============================================== */

Game of Thrones I Solution in Java

import java.io.*;

public class Solution {

    public static void solve(Input in, PrintWriter out) throws IOException {
        String s = in.next();
        int[] counts = new int[26];
        for (char c : s.toCharArray()) {
            counts[c - 'a']++;
        }
        int odd = 0;
        for (int count : counts) {
            if (count % 2 == 1) {
                odd++;
            }
        }
        out.println(odd <= 1 ? "YES" : "NO");
    }

    public static void main(String[] args) throws IOException {
        PrintWriter out = new PrintWriter(System.out);
        solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
        out.close();
    }

    static class Input {
        BufferedReader in;
        StringBuilder sb = new StringBuilder();

        public Input(BufferedReader in) {
            this.in = in;
        }

        public Input(String s) {
            this.in = new BufferedReader(new StringReader(s));
        }

        public String next() throws IOException {
            sb.setLength(0);
            while (true) {
                int c = in.read();
                if (c == -1) {
                    return null;
                }
                if (" \n\r\t".indexOf(c) == -1) {
                    sb.append((char)c);
                    break;
                }
            }
            while (true) {
                int c = in.read();
                if (c == -1 || " \n\r\t".indexOf(c) != -1) {
                    break;
                }
                sb.append((char)c);
            }
            return sb.toString();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }
    }
}

Game of Thrones I Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
word = list(raw_input())
lst = {}
for i in word:
    if lst.get(i):
        lst[i] = (lst[i]+1)%2
    else:
        lst[i] = 1
sm = 0
for i in lst:
    sm = sm +lst[i]
if (len(word)%2 ==0 and sm ==0) or (len(word)%2 ==1 and sm ==1):
    print "YES"
else:
    print "NO"

Game of Thrones I Solution using JavaScript

process.stdin.resume();
process.stdin.setEncoding("ascii");
var data = "";
process.stdin.on("data", function (input) {
    data += input;
    
});

process.stdin.on('end', function() {
    var input = data.trim().toLowerCase();
    var chars = {}
    for(var i = 0; i < input.length; i++){
        if(chars[input[i]] == null){
            chars[input[i]] = 1;
        }else{
            chars[input[i]]++;
        }
    }
    var liho = 0;
    for(var ch in chars){
        if(chars[ch]%2==1){
            liho++;
        }
    }
    if(liho > 1){
        console.log("NO");
    }else{
        console.log("YES");
    }
});

Game of Thrones I Solution in Scala

object Solution {

  def main(args: Array[String]) {
    val input = Console.readLine().trim
    val out = checker(input)
    println(output(out))

  }

  def samePairs(s: String): Boolean = {
    s.sliding(2, 2).forall {
      word =>
        word.length == 2 && word.charAt(0) == word.charAt(1)
    }
  }

  def output(b: Boolean): String = if (b) "YES" else "NO"

  def oddChar(s: String): Set[Char] = {
    val filtered = ('a' to 'z').map {
      c =>
        c -> s.count(_ == c)
    }.filter(_._2 % 2 == 1)
    filtered.map(_._1).toSet
  }

  def checker(inputIn: String): Boolean = {
    val input = inputIn.sorted
    // even length
    if (input.length % 2 == 0) {
      samePairs(input)
    } else {
      val charSet = oddChar(input)
      var ret = false
      for {
        c <- charSet
      } {
        val idx = input.indexOf(c)
        val filtered = input.take(idx) ++ input.drop(idx + 1)
        val result = checker(filtered)
        if (result) {
          ret = result
          return ret
        }
      }
      ret
    }
  }
}

Game of Thrones I Solution in Pascal

(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
uses math;
var  n,m,ans:int64;
     i:longint;
     s:ansistring;
 begin
 readln(s);
 readln(n);
 m:=length(s);
 for i:=1 to length(s) do
  if (s[i]='a') then inc(ans);
  ans:=(n div m)*ans;

  for i:=1 to n mod m do
  if s[i]='a' then inc(ans);
writeln(ans);
 end.

Disclaimer: This problem (Game of Thrones I) 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.

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