Program to find starting index of the child who receives last balloon in Python?

PythonServer Side ProgrammingProgramming

Suppose we have n children standing in a circle, and they are waiting to get a balloon. The distribution is carried out starting with the kth child (first at index 0), and giving them a balloon they left the circle. Now every kth child gets a balloon going clockwise until there is only one child left that gets a balloon. So if we have n and k, we have to find the starting index of the child that receives the last balloon.

So, if the input is like n = 3 k = 2, then the output will be 1, in the first round, child 2 gets a balloon, and leave so the circle will be [0, 1]. In second round, child 0 gets a balloon, circle will be [1].

To solve this, we will follow these steps:

  • arr := a new list from range 0 to n

  • init := 0

  • while size of arr > 1, do

    • remove := (init + k) mod size of arr

    • delete arr[remove]

    • init := remove

  • return arr[0]

Let us see the following implementation to get better understanding:

Example

 Live Demo

class Solution:
   def solve(self, n, k):
      arr = list(range(0, n))
      init = 0
      while len(arr) > 1:
         remove = (init + k) % len(arr)
         del arr[remove]
         init = remove
      return arr[0]

ob = Solution()
n = 3
k = 2
print(ob.solve(n, k))

Input

3,2

Output

1
raja
Updated on 10-Nov-2020 07:50:58

Advertisements