Program to check whether first player can win a game where players can form string char by char in C++

Suppose we have a list of words. Now consider a ghost game where two players can participate into it. Here players alternate appending letters to a string. And the string that is being made must be a valid prefix of a word in the list, and the player who spells out any word in the list loses. We have to check whether the first player can win or not if both players are playing optimally.

So, if the input is like words = ["manage", "manager", "min"], then the output will be True, as they can play like −

  • m [Player 1]
  • ma [Player 2]
  • man [Player 1]
  • mana [Player 2]
  • manag [Player 1]
  • manage [Player 2] Lose

So player 1 wins.

To solve this, we will follow these steps −

  • Define one map mp
  • for each word it in words, do
    • ch := it[0]
    • insert it into mp[ch]
  • mn := inf
  • for each key-value pair it in mp, do
    • str := value of it
    • size := size of str
    • if size mod 2 is same as 0, then −
      • return 1
    • return 0

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<string> &words) {
   map<char, set<string>> mp;
   for (auto &it : words) {
      char ch = it[0];
   int mn = INT_MAX;
   for (auto &it : mp) {
      string str = *(it.second.begin());
      int size = str.size();
      if (size % 2 == 0)
         return 1;
   return 0;
int main(){
   vector<string> v = {"manage", "manager", "min"};
   cout << solve(v);


{"manage", "manager", "min"}



Updated on: 12-Dec-2020


Kickstart Your Career

Get certified by completing the course

Get Started