O(nlogn) Algorithm - Find three evenly spaced ones within binary string

前端 未结 30 2944
刺人心
刺人心 2020-11-28 00:07

I had this question on an Algorithms test yesterday, and I can\'t figure out the answer. It is driving me absolutely crazy, because it was worth about 40 points. I figure

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 00:55

    One inroad into the problem is to think of factors and shifting.

    With shifting, you compare the string of ones and zeroes with a shifted version of itself. You then take matching ones. Take this example shifted by two:

    1010101010
      1010101010
    ------------
    001010101000
    

    The resulting 1's (bitwise ANDed), must represent all those 1's which are evenly spaced by two. The same example shifted by three:

    1010101010
       1010101010
    -------------
    0000000000000
    

    In this case there are no 1's which are evenly spaced three apart.

    So what does this tell you? Well that you only need to test shifts which are prime numbers. For example say you have two 1's which are six apart. You would only have to test 'two' shifts and 'three' shifts (since these divide six). For example:

    10000010 
      10000010 (Shift by two)
        10000010
          10000010 (We have a match)
    
    10000010
       10000010 (Shift by three)
          10000010 (We have a match)
    

    So the only shifts you ever need to check are 2,3,5,7,11,13 etc. Up to the prime closest to the square root of size of the string of digits.

    Nearly solved?

    I think I am closer to a solution. Basically:

    1. Scan the string for 1's. For each 1 note it's remainder after taking a modulus of its position. The modulus ranges from 1 to half the size of the string. This is because the largest possible separation size is half the string. This is done in O(n^2). BUT. Only prime moduli need be checked so O(n^2/log(n))
    2. Sort the list of modulus/remainders in order largest modulus first, this can be done in O(n*log(n)) time.
    3. Look for three consecutive moduli/remainders which are the same.
    4. Somehow retrieve the position of the ones!

    I think the biggest clue to the answer, is that the fastest sort algorithms, are O(n*log(n)).

    WRONG

    Step 1 is wrong as pointed out by a colleague. If we have 1's at position 2,12 and 102. Then taking a modulus of 10, they would all have the same remainders, and yet are not equally spaced apart! Sorry.

提交回复
热议问题