LeetCode 1756. Design Most Recently Used Queue Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1756. Design Most Recently Used Queue

Description

Design a queue-like data structure that moves the most recently used element to the end of the queue.

Implement the MRUQueue class:

  • MRUQueue(int n) constructs the MRUQueue with n elements: [1,2,3,...,n].
  • int fetch(int k) moves the kth element (1-indexed) to the end of the queue and returns it.

 

Example 1:

Input:
["MRUQueue", "fetch", "fetch", "fetch", "fetch"]
[[8], [3], [5], [2], [8]]
Output:
[null, 3, 6, 2, 2]

Explanation:
MRUQueue mRUQueue = new MRUQueue(8); // Initializes the queue to [1,2,3,4,5,6,7,8].
mRUQueue.fetch(3); // Moves the 3rd element (3) to the end of the queue to become [1,2,4,5,6,7,8,3] and returns it.
mRUQueue.fetch(5); // Moves the 5th element (6) to the end of the queue to become [1,2,4,5,7,8,3,6] and returns it.
mRUQueue.fetch(2); // Moves the 2nd element (2) to the end of the queue to become [1,4,5,7,8,3,6,2] and returns it.
mRUQueue.fetch(8); // The 8th element (2) is already at the end of the queue so just return it.

 

Constraints:

  • 1 <= n <= 2000
  • 1 <= k <= n
  • At most 2000 calls will be made to fetch.

 

Follow up: Finding an O(n) algorithm per fetch is a bit easy. Can you find an algorithm with a better complexity for each fetch call?

Solutions

Solution 1

PythonJavaC++GoTypeScript
class MRUQueue: def __init__(self, n: int): self.q = list(range(1, n + 1)) def fetch(self, k: int) -> int: ans = self.q[k - 1] self.q[k - 1 : k] = [] self.q.append(ans) return ans # Your MRUQueue object will be instantiated and called as such: # obj = MRUQueue(n) # param_1 = obj.fetch(k)(code-box)

Solution 2

Python
class BinaryIndexedTree: def __init__(self, n: int): self.n = n self.c = [0] * (n + 1) def update(self, x: int, v: int): while x <= self.n: self.c[x] += v x += x & -x def query(self, x: int) -> int: s = 0 while x: s += self.c[x] x -= x & -x return s class MRUQueue: def __init__(self, n: int): self.q = list(range(n + 1)) self.tree = BinaryIndexedTree(n + 2010) def fetch(self, k: int) -> int: l, r = 1, len(self.q) while l < r: mid = (l + r) >> 1 if mid - self.tree.query(mid) >= k: r = mid else: l = mid + 1 x = self.q[l] self.q.append(x) self.tree.update(l, 1) return x # Your MRUQueue object will be instantiated and called as such: # obj = MRUQueue(n) # param_1 = obj.fetch(k)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !