Elimination Game in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of sorted integers from 1 to n. That is starting from left and ending at right, we have to remove the first number and every other number afterward until we reach the end of the list. We will repeat the previous step again, but this time from right to left, remove the right most number and every other number from the remaining numbers. We will repeat the steps again, alternating left to right and right to left, until one single number remains. We have to find the last number that remains starting with a list of length n.

So if the input is like n = 9, then the steps will be as follows −

  • 1,2,3,4,5,6,7,8,9

  • 2,4,6,8

  • 2,6

  • 6

So the answer will be 6.

To solve this, we will follow these steps −

  • left := 1, head := 1, step := 1, rem := n

  • while rem > 1

    • if left is non zero or rem is odd, then head := head + step

    • step := step * 2

    • left := inverse of left

    • rem := rem / 2

  • return head

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int lastRemaining(int n) {
      int head = 1;
      int step = 1;
      int rem = n;
      int left = 1;
      while(rem > 1){
         if(left || rem % 2 == 1){
            head += step;
         }
         step *= 2;
         left = !left;
         rem /= 2;
      }
      return head;
   }
};
main(){
   Solution ob;
   cout << (ob.lastRemaining(9));
}

Input

9

Output

6
raja
Published on 02-May-2020 11:48:13
Advertisements