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

前端 未结 30 2945
刺人心
刺人心 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:30

    Obviously we need to at least check bunches of triplets at the same time, so we need to compress the checks somehow. I have a candidate algorithm, but analyzing the time complexity is beyond my ability*time threshold.

    Build a tree where each node has three children and each node contains the total number of 1's at its leaves. Build a linked list over the 1's, as well. Assign each node an allowed cost proportional to the range it covers. As long as the time we spend at each node is within budget, we'll have an O(n lg n) algorithm.

    --

    Start at the root. If the square of the total number of 1's below it is less than its allowed cost, apply the naive algorithm. Otherwise recurse on its children.

    Now we have either returned within budget, or we know that there are no valid triplets entirely contained within one of the children. Therefore we must check the inter-node triplets.

    Now things get incredibly messy. We essentially want to recurse on the potential sets of children while limiting the range. As soon as the range is constrained enough that the naive algorithm will run under budget, you do it. Enjoy implementing this, because I guarantee it will be tedious. There's like a dozen cases.

    --

    The reason I think that algorithm will work is because the sequences without valid triplets appear to go alternate between bunches of 1's and lots of 0's. It effectively splits the nearby search space, and the tree emulates that splitting.

    The run time of the algorithm is not obvious, at all. It relies on the non-trivial properties of the sequence. If the 1's are really sparse then the naive algorithm will work under budget. If the 1's are dense, then a match should be found right away. But if the density is 'just right' (eg. near ~n^0.63, which you can achieve by setting all bits at positions with no '2' digit in base 3), I don't know if it will work. You would have to prove that the splitting effect is strong enough.

提交回复
热议问题