Waiter

  • + 0 comments

    Very confusing question with very poor explanation of what it's asking you to do. Essentially, what it wants you to do is do q iterations where each iteration corresponds to a prime starting from 2 (iteration 0=2, iteration 1=3, iteration 2=5, etc), and see if that given prime is a factor of a value in the array. If the prime is a factor move the value to an answer array, if not move the number to some new array. Remember this question is about a STACK of plates, if the prime is a factor of a value that values plate stays in place, but if not it gets moved to a seperate stack.

    example: input [4, 3, 2, 7, 11], doing one iteration so the prime is 2 4 is at the bottom of the stack of plates, 11 is the top. 2 is a factor of both 4 & 2, so those plates stay in that stack [4, 2], but for 3, 7, & 11, 11 is now at the bottom. [11, 7, 3]. After doing all the iterations(in this example we're doing 1 to reiterate) the question says store the remaining plates top to bottom, so the final answer stack becomes [4, 2, 3, 7, 11]

    If we were to do the same example again but with two iterations: On iteration 0 we end up same as before with two stacks ans: [4, 2], remaining: [11, 7, 3]. Now on iteration 1, 3 is prime factor we are checking for. 3 is a prime factor of 3 so we lift that into ans [4, 2, 3], the remaining stack ends up flipped to [7, 11]. Since we've done our two iterations, we move the remaining numbers to the ans stack, which means flipping them again so the final ans stack becomes [4, 2, 3, 11, 7].

    Hope this clarifies a little about what exactly this question wants you to do.

    Heres an inplace C++ solution.

    // precalculate primes up to 10k (1229 primes), max possible input number is 10000, max iteration is 1200
    int primes[] = {2, 3, ..., 9973};
    
    vector<int> waiter(vector<int> number, int q) {
        auto it = number.begin();
        for (int i = 0; i < q; i++) {
            // if it can't be partitioned further
            if (it == number.end()) {
                return number;
            }
            // get prime
            int divisor = primes[i];
            // stable partition to keep relative order, if prime is factor, value moved to left partition
            it = stable_partition(it, number.end(), [&](int x) { return x % divisor == 0; });
            // as the plates are on a stack need to be reversed, "top" is now "bottom"
            reverse(it, number.end());
        }
        // store remaining plates top to bottom which means reversing again.
        reverse(it, number.end());
        return number;
    }