The Minion Game : HackerRank Solution in Python

Kevin and Stuart want to play the ‘The Minion Game’.

Game Rules

Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.

Scoring
A player gets +1 point for each occurrence of the substring in the string S.

For Example:
String S = BANANA
Kevin’s vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.

For better understanding, see the image below:

Your task is to determine the winner of the game and their score.

Solution in Python 3

TMG (github.com)

def minion_game(string):
s=len(string)
vowel = 0
consonant = 0

for i in range(s):
if string[i] in 'AEIOU':
vowel+=(s-i)
else:
consonant+=(s-i)

if vowel < consonant:
print('Stuart ' + str(consonant))
elif vowel > consonant:
print('Kevin ' + str(vowel))
else:
print('Draw')

Explanation

To start with, we store the length of the given string in a variable called s.

s=len(string)

and declare two variables vowel and consonant and initialize them to 0

vowel=0

consonant=0

Then we iterate over the length of the string i.e s through a variable i using a for loop.

for i in range(s):

In the for loop, if character at index i of string is a vowel then we increment vowel by (s-i), else if string at index i is not a vowel then we increment consonant by (s-i).

for i in range(s):
if string[i] in 'AEIOU':
vowel+=(s-i)
else:
consonant+=(s-i)

To further understand above for loop let’s look at an example, if string = ‘BANANA’.

When i = 0, character at string[i] is a consonant (as ‘BANANA’[0] = ‘B’) and we increment consonant by (s-i) which equals to 6 as here s = 6 and i = 0, We do this because starting from ‘B’ there are six possible words (or substrings) that can be formed. [‘B’, ‘BA’, ‘BAN’, ‘BANA’, ‘BANAN’, ‘BANANA’]. On subsequent iterations when string[i] is a consonant at indices 2 and 4, we add additional substrings or the same substrings with additional instances.

Subsequently after the execution of the above for loop, if vowel is less than consonant we print Stuart along with value of consonant and else if vowel is greater than consonant we print Kevin along with the value of vowel, and if both are equal we print ‘Draw’.

if vowel < consonant:
print('Stuart ' + str(consonant))
elif vowel > consonant:
print('Kevin ' + str(vowel))
else:
print('Draw')

pretending to teach is one of the best way to learn.