Friday, April 8, 2016

Waiter - HackerRank

You are a waiter at a party. There are NN stacked plates. Each plate has a number written on it. You start picking up the plates from the top one by one and check whether the number written on the plate is divisible by PP(a prime). The starting value of PP is 22. If the number is divisible, you stack that plate separately with other PP divisible plates. If not, you stack that plate separately with the other plates that are not divisible by PP.

In the next iteration, the value of PP changes to the next prime number after PP. You check the plates from the pile that were not divisible by PP in the last iteration. You repeat this process a number of times. By doing this process QQ times, you end up getting different piles of plates. The plates that are not divisible by the QthQth prime (which is our last iteration), from the last pile of plates. Say you have MM (it is clear that MM is either QQ or Q+1Q+1) different piles of plates. Starting from the first pile, print the number written on the plate while removing plates from a pile in the same order as described above. Do this process for all the MM piles. Print one value in a single line.

First of all, generate primes using Sieve, or copy-paste a list of pre-generated primes. After each iteration the order of the remaining plates is reversed (you put the last on top and once finished you start from the top). That means that the solution has to have a stack, not a queue.