Bowling Pins

Problem Statement :

Bowling is a sport in which a player rolls a bowling ball towards a group of pins, the target being to knock down the pins at the end of a lane.

In this challenge, the rules of the game are slightly modified. Now, there are a given number of pins, and the pins are arranged in a horizontal line instead of a triangular formation. Two players have to play this game, taking alternate turns. Whoever knocks down the last pin(s) will be declared the winner.

You are playing this game with your friend, and both of you have become proficient at it. You can knock down any single pin, or any two adjacent pins at one throw of a bowling ball, however, these are the only moves that you can perform. Some moves have already been played. Suddenly, you realize that it is possible to determine whether this game can be won or not, assuming optimal play. And luckily it's your turn right now.

A configuration is represented by a string consisting of the letters X and I, where:

I represents a position containing a pin.
X represents a position where a pin has been knocked down.
An example of such a configuration is shown in the image below. Here, the number of pins is , and the  pin has already been knocked down.

Its representation will be IXIIIIIIIIIII.

Complete the function isWinning that takes the number of pins and the configuration of the pins as input, and return WIN or LOSE based on whether or not you will win.

Given the current configuration of the pins, if both of you play optimally, determine whether you will win this game or not.


A player has to knock down at least one pin in his turn.
Both players play optimally.
Input Format

The first line contains an integer, , the number of test cases. Then  test cases follow.

For each test case, the first line contains a single integer , denoting the number of pins. The second line contains a string of  letters, where each letter is either I or X.

Output Format

For each test case, print a single line containing WIN if you will win this game, otherwise LOSE.

Solution :


                            Solution in C :

In  C  :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char str[301];
int dp[301],a[4000];

int main(){
  int T,N,c,i,j;
      else if(str[i]=='X' && i && str[i-1]=='I'){
  return 0;

                        Solution in C++ :

In  C++  :

#include <cmath>
#include <cstdio>
#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

const int Maxn = 305;

int nim[Maxn];
int t;
int n;
char str[Maxn];

int main() {
    for (int i = 1; i < Maxn; i++) {
        set <int> S;
        for (int j = 0; j < i; j++)
            S.insert(nim[j] ^ nim[i - 1 - j]);
        for (int j = 0; j + 1 < i; j++)
            S.insert(nim[j] ^ nim[i - 2 - j]);
        while (S.find(nim[i]) != S.end()) nim[i]++;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        scanf("%s", str);
        int res = 0;
        for (int i = 0; i < n; i++) if (str[i] == 'I') {
            int j = i;
            while (j < n && str[j] == 'I') j++;
            res ^= nim[j - i];
            i = j;
        printf("%s\n", res? "WIN": "LOSE");
    return 0;

                        Solution in Java :

In  Java :

import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

	static int[] nim = new int[301];

	public static void main(String[] args) {
		Scanner in = new Scanner(;
		int t = in.nextInt();
		while(t-- > 0) {
			int n = in.nextInt();
			String s =;
			List<Integer> list = new ArrayList<Integer>();
			int count = 0;
			for(int i = 0; i < s.length(); i++) {
				char ch = s.charAt(i);
				if(ch == 'I') {
				} else {
					if(count != 0)
					count = 0;
			if(count > 0)

			int result = 0;
			for(int i = 0; i < list.size(); i++) {
				result ^= grundy(list.get(i));
			if(result <= 0) {
			} else {

	private static int mex(List<Integer> arr) {
		int mex = 0;
		return mex;

	private static int grundy(int n) {
		if(nim[n] != 0)
			return nim[n];
		if(n == 0) {
			nim[0] = 0;
			return 0;
		if (n == 1) {
			nim[1] = 1;
	        return (1);
	    if (n == 2) {
			nim[2] = 2;
	        return (2);

		List<Integer> list = new ArrayList<Integer>();
		for(int i = 1, j = 0, k = 0; i <= n; i++) {
			int x, y;
			if(i <= n / 2) {
				x = grundy(j);
				y = grundy(n - j - 2);
			} else {
				x = grundy(k);
				y = grundy(n - k - 1);
			list.add(x ^ y);
		nim[n] = mex(list);
		return nim[n];

                        Solution in Python : 
In  Python3 :

def game_from(board: str) -> list:
    game = []
    count = 0
    for c in board:
        if c == 'I':
            count += 1
        elif count > 0:
            count = 0
    if count > 0:
    return game

def moves_for(n: int, hits: [int]) -> [list]:
    moves = []
    for hit in hits:
        left = 0
        right = n - hit
        while left <= right:
            if left == 0 and right == 0:
            elif right < 1 <= left:
            elif left < 1 <= right:
                moves.append([left, right])
            left += 1
            right -= 1
    return moves

def mex_of(s: set) -> int:
    mex = 0
    while mex in s:
        mex += 1
    return mex

def g_of(n: int, cache: dict) -> int:
    if n < 3:
        return n
        result = cache.get(n, None)
        if result is not None:
            return result
        moves = moves_for(n, [1,2])
        s = set()
        for move in moves:
            if len(move) == 1:
                s.add(g_of(move[0], cache))
                s.add(g_of(move[0], cache) ^ g_of(move[1], cache))
        result = mex_of(s)
        cache[n] = result
        return result

def winner(board: str, cache: dict) -> str:
    game = game_from(board)
    g = 0
    for i in game:
        g ^= g_of(i, cache)
    return 'WIN' if g != 0 else 'LOSE'

n = int(input().strip())
c = {}

for i in range(n):
    g = list(input().strip())
    print(winner(g, c))

View More Similar Problems

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →