Suppose, we are asked to design a queue that moves the most recently used element to the end of it. The queue will be initialized with integer numbers 1 to n. Now we have to build a function so that whenever it is called, it moves the value from the position given as its input to the end of the queue. We will call the function multiple times, and the function will return the value currently at the end of the queue while performing its moving task.
So, if the queue is initialized with a value n = 5, or it contains values from 1 to 5.; and the positions where the move is performed are 5, 2, 3, and 1 respectively, then the output will be 5, 2, 4, 1
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
from bisect import bisect_right from math import sqrt class TestQueue: def __init__(self, n): self.n = n self.nn = int(sqrt(n)) self.data =  self.index =  for i in range(1, n+1): ii = (i-1)//self.nn if ii == len(self.data): self.data.append() self.index.append(i) self.data[-1].append(i) def solve(self, k): i = bisect_right(self.index, k)-1 x = self.data[i].pop(k - self.index[i]) for ii in range(i+1, len(self.index)): self.index[ii] -= 1 if len(self.data[-1]) >= self.nn: self.data.append() self.index.append(self.n) self.data[-1].append(x) if not self.data[i]: self.data.pop(i) self.index.pop(i) return x queue = TestQueue(5) print(queue.solve(5)) print(queue.solve(2)) print(queue.solve(3)) print(queue.solve(1))
queue = TestQueue(5) print(queue.solve(5)) print(queue.solve(2)) print(queue.solve(3)) print(queue.solve(1))
5 2 4 1