Sunday, June 30, 2013

Remove every kth element (Josephus problem)

Problem:
There are n nodes in a circle and you will start removing every kth node from it until there is only one node left.

Design a datastructure which will allow above in O(n) time

Solution:
This is known as a Josephus problem. A solution is as follows: after removing kth element we end up with (n-1) elements left, and should then remove a kth element starting with the (k+1) element from the original sequence. Obviously, if we do that on the actual data structure, we'll need O(n^2) operations. So instead we should use modular arithmetic and simply find out the index of a remaining element. This can be done in O(n) time as follows:

def josephus(n, k):
   if n ==1:
     return 1
   else:
     return ((josephus(n-1,k)+k-1) % n)+1

This can also be implemented as a loop w/o recursion.
The answer to the original question is: a simple array will do.

Complexity:
time - O(n)
space - O(1)
Links and credits:
http://www.careercup.com/question?id=20318662
http://en.wikipedia.org/wiki/Josephus_problem

No comments:

Post a Comment