Skip to content
thecscience
THECSICENCE

Learn everything about computer science

  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
thecscience
THECSICENCE

Learn everything about computer science

HackerRank Gaming Array Problem Solution

Yashwant Parihar, June 13, 2023August 1, 2024

In this post, we will solve HackerRank Gaming Array Problem Solution.

Andy wants to play a game with his little brother. Bob. The game starts with an array of distinct integers and the rules are as follows:

  • Bob always plays first.
  • In a single move, a player chooses the maximum element in the array. He removes it and all elements to its right. For example, if the starting array arr[2, 3, 5, 4, 1], then it becomes arr’ = [2, 3] after removing [5, 4, 1].
  • The two players alternate turns.
  • The last player who can make a move wins.
    Andy and Bob play g games. Given the initial array for each game, find and print the name of the winner on a new line. If Andy wins, print ANDY; if Bob wins, print BOB.
    To continue the example above, in the next move Andy will remove 3. Bob will then remove 2 and win because there are no more integers to remove.
    Returns
  • string: either ANDY or BOB

Function Description
Complete the gamingArray function in the editor below.
gamingArray has the following parameter(s):
int arr[n]: an array of integers

Input Format
The first line contains a single integer g, the number of games.
Each of the next g pairs of lines is as follows:

  • The first line contains a single integer, n, the number of elements in arr.
  • The second line contains n distinct space-separated integers arr[i] where 0 < i < n.

Sample Input 0

2
5
5 2 6 3 4
2
3 1

Sample Output 0

ANDY
BOB
HackerRank Gaming Array Problem Solution
HackerRank Gaming Array Problem Solution

Gaming Array C Solution

//Import necessary files
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

//Main function
int main()
{
    //Variables definition
    int j, t, n, contador, maior;
    //Get the games' number
    scanf("%d", &j);
    //For each game...
    for (int jogo = 0; jogo < j; jogo++)
    {
        //Get vector size
        scanf("%d", &t);
        //Initialize control variables
        contador = 0;
        maior = 0;
        //For each supposed vector position...
        for (int i = 0; i < t; i++)
        {
            //Get number
            scanf("%d", &n);
            //Check if it's the bigger one
            if (n > maior)
            {
                //Changes the biggest number
                maior = n;
                //Increment counter
                contador++;
            }
        }
        //Print result
        printf(((contador % 2) == 0) ? "ANDY\n" : "BOB\n");
    }
    //Return default value (no error)
    return 0;
}

Gaming Array C++ Solution

/* You lost the game. */

#include <list>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cfloat>
#include <numeric>
#include <cassert>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include <vector>

#define L long long int
#define VL vector<L>
#define VI vector<int>
#define VVI vector<VI>
#define PII pair<int, int>
#define VPII vector<PII>
#define fin(i,n) for(int i = 0; i < n; i++)
#define fin2(i,a,b) for(int i = a; i < b; i++)

using namespace std;



int main() {
    int g,n,m,c,res;
    scanf("%d", &g);
    fin(i, g) {
        res = 0;
        m = 0;
        scanf("%d", &n);
        fin(j, n) {
            scanf("%d", &c);
            if (c > m) { res++; m = c; }
        }
        if (res % 2 == 1) { printf("BOB\n"); }
        else { printf("ANDY\n"); }
    }
    return 0;
}

Gaming Array C Sharp Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class Solution {
    
    static int RemoveMax(int[] a, int l){
        int max=0;
        int maxIdx=0;
        //var newArray=new int[a.Length];
        int maxCount=0;
        for (var i=0; i<l; i++){
            if (max<a[i]){
                max=a[i];
                
                /*
                  for (var j=maxIdx; j<i; j++){
                        newArray[j]=a[j];
                    }
                */
                maxIdx=i;
                maxCount++;
            }
        }
        
      //Array.Resize(ref a, maxIdx);
        
        return maxCount%2;
        
    }
    
    static string FindWinner(int[] a){
        string Winner="ANDY";
        int l=a.Length;
        /*
        while (l>0){
            l=RemoveMax(a, l);
            Winner=Winner=="ANDY"?"BOB":"ANDY";
        }
        */
        var w=RemoveMax(a, l);
        
        
        return w==1?"BOB":"ANDY";
    }

    static void Main(String[] args) {
        int g = Convert.ToInt32(Console.ReadLine());
        for(int a0 = 0; a0 < g; a0++){
            int n = Convert.ToInt32(Console.ReadLine());
            string[] a_temp = Console.ReadLine().Split(' ');
            int[] a = Array.ConvertAll(a_temp,Int32.Parse);
            
            Console.WriteLine(FindWinner(a));
            
            
            
        }
    }
}

Gaming Array 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 'gamingArray' function below.
     *
     * The function is expected to return a STRING.
     * The function accepts INTEGER_ARRAY arr as parameter.
     */

    public static String gamingArray(List<Integer> arr) {
            Map<Integer, Integer> map = new HashMap<>();
        Queue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < arr.size(); i++) {
            int inv = arr.get(i) * -1;
            pq.add(inv);
            map.put(arr.get(i), i);
        }
        int turn = 1;
        int cur = arr.size() - 1;
        while (true) {
            while (true) {
                int max = pq.poll() * -1;
                int index = map.get(max);
                if (index <= cur) {
                    cur = index;
                    break;
                }
            }
            if (cur == 0) break;
            if (turn == 0) turn = 1;
            else turn = 0;
        }
        if (turn == 0)
            return "ANDY";
        return "BOB";
    }

}

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 arrCount = Integer.parseInt(bufferedReader.readLine().trim());

                List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                    .map(Integer::parseInt)
                    .collect(toList());

                String result = Result.gamingArray(arr);

                bufferedWriter.write(result);
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}

Gaming Array 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 g = parseInt(readLine());
    for(var a0 = 0; a0 < g; a0++){
        var n = parseInt(readLine());
        var arr = readLine().split(" ").map(Number);
        var winner = ArrayGame.findWinner(arr);
        console.log(winner);
    }

}

class ArrayGame {
	static findWinner(arr) {
		var max = 0;
		var maxCount = 0;
		for(var i = 0 ; i < arr.length ; i++) {
			if(arr[i] >= max) {
				maxCount++;
				max = arr[i];
			}
		}
		return (maxCount % 2) ? "BOB" : "ANDY";
	}
}

Gaming Array Python Solution

#!/bin/python3

import sys


g = int(input().strip())
for a0 in range(g):
    n = int(input().strip())
    nums = list(map(int, input().split()))

    maxi = [None] * (n)
    maxv = [None] * (n)
    
    maxi[0] = 0
    maxv[0] = nums[0]
    
    for i in range(1, n):
        if (nums[i] > maxv[i-1]):
            maxi[i] = i
            maxv[i] = nums[i]
        else:
            maxi[i] = maxi[i-1]
            maxv[i] = maxv[i-1]
            
    if (len(set(maxi)) % 2 == 0):
        print("ANDY")
    else:
        print("BOB")
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post
  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 THECSICENCE | WordPress Theme by SuperbThemes