Editorial for DMOPC '20 Contest 4 P1 - Missing Numbers

Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.

Author: 4fecta

Note that the sum of all numbers from 1 to N is \frac{N(N+1)}{2}, which we will denote as M. To avoid overcounting, we will only count pairs (i, j) with i < j.

Subtask 1

We can loop over all \mathcal{O}(N^2) pairs of numbers (i, j) and check if M - i - j = S.

Time complexity: \mathcal{O}(TN^2)

Subtask 2

To speed the previous solution up, note that there is at most one valid j for each i. Thus, we can loop all i and check if there is a j such that j \in (i, N] and M - i - j = S.

Time complexity: \mathcal{O}(TN)

Subtask 3

For full marks, note that the average of all valid pairs (i, j) must be constant since their sum is constant. We can compute the required average of (i, j), find the pair with the required average and minimal j-i (intuitively closest to the average), and imagine "expanding" the pair to (i-1, j+1) repeatedly until either i = 1 or j = N. The number of pairs can thus be computed with a simple subtraction.

Time complexity: \mathcal{O}(T)


Can you solve the problem if Jennifer erases K numbers in general instead of just 2?


  • -1
    YassineAllala  commented on March 28, 2021, 7:28 a.m.

    I've tried to use a formula for the problem and it doesn't seem to work? Why?

    Here's my algorithm: let x be the difference between the real sum (N*(N+1)/2 and S, the number of possible pairs possible to form the sum x can be found by the integer (x-1)/2, I've tried it for big values and it's about the same and working, why not here?

    • 4
      Tony1234  commented on March 28, 2021, 8:26 a.m. edited

      What if N \le X, this means that the pair 1, N will not work. You must consider cases where N \le X

  • 0
    humbertoyusta  commented on March 15, 2021, 6:23 p.m.

    What is the expected complexity of the bonus?, I only know how to solve it in O(n^4).

    • 1
      4fecta  commented on March 15, 2021, 9:37 p.m.

      To be honest, we're not quite sure either! The bonus section was added to inspire some further thinking for those who have already solved the original problem. If you've found an interesting or fast algorithm that solves it, please let us know here! :D

  • 2
    piddddgy  commented on March 15, 2021, 10:44 a.m.

    wait can u go over the "simple subtraction" pls

    • someone who bsearched

    • 5
      humbertoyusta  commented on March 15, 2021, 11:29 a.m.

      If the average is X, all pairs must be of the form (X-K, X+K), for some K, such that X-K and X+K are integers between 1 and n, so there will be min(N-ceil(K)+1, floor(K)) - [K is an integer](for not taking into account equal numbers) pairs.