Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

前端 未结 30 2010
时光说笑
时光说笑 2020-11-22 07:02

I had an interesting job interview experience a while back. The question started really easy:

Q1: We have a bag containing numbers

30条回答
  •  再見小時候
    2020-11-22 07:57

    Yet another way is using residual graph filtering.

    Suppose we have numbers 1 to 4 and 3 is missing. The binary representation is the following,

    1 = 001b, 2 = 010b, 3 = 011b, 4 = 100b

    And I can create a flow-graph like the following.

                       1
                 1 -------------> 1
                 |                | 
          2      |     1          |
    0 ---------> 1 ----------> 0  |
    |                          |  |
    |     1            1       |  |
    0 ---------> 0 ----------> 0  |
                 |                |
          1      |      1         |
    1 ---------> 0 -------------> 1
    

    Note that the flow graph contains x nodes, while x being the number of bits. And the maximum number of edges are (2*x)-2 .

    So for 32 bit integer it will take O(32) space or O(1) space.

    Now if I remove capacity for each number starting from 1,2,4 then I am left with a residual graph.

    0 ----------> 1 ---------> 1
    

    Finally I shall run a loop like the following,

     result = []
     for x in range(1,n):
         exists_path_in_residual_graph(x)
         result.append(x)
    

    Now the result is in result contains numbers that are not missing as well(false positive). But the k <= (size of the result) <= n when there are k missing elements.

    I shall go through the given list one last time to mark the result missing or not.

    So the time complexity will be O(n) .

    Finally, it is possible to reduce the number of false positive(and the space required) by taking nodes 00,01,11,10 instead of just 0 and 1.

提交回复
热议问题