Skip to content

Commit 486f283

Browse files
committed
Sync LeetCode submission Runtime - 15 ms (91.77%), Memory - 19 MB (76.88%)
1 parent a1748fb commit 486f283

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<p>Design a queue-like data structure that moves the most recently used element to the end of the queue.</p>
2+
3+
<p>Implement the <code>MRUQueue</code> class:</p>
4+
5+
<ul>
6+
<li><code>MRUQueue(int n)</code> constructs the <code>MRUQueue</code> with <code>n</code> elements: <code>[1,2,3,...,n]</code>.</li>
7+
<li><code>int fetch(int k)</code> moves the <code>k<sup>th</sup></code> element <strong>(1-indexed)</strong> to the end of the queue and returns it.</li>
8+
</ul>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong>
15+
[&quot;MRUQueue&quot;, &quot;fetch&quot;, &quot;fetch&quot;, &quot;fetch&quot;, &quot;fetch&quot;]
16+
[[8], [3], [5], [2], [8]]
17+
<strong>Output:</strong>
18+
[null, 3, 6, 2, 2]
19+
20+
<strong>Explanation:</strong>
21+
MRUQueue mRUQueue = new MRUQueue(8); // Initializes the queue to [1,2,3,4,5,6,7,8].
22+
mRUQueue.fetch(3); // Moves the 3<sup>rd</sup> element (3) to the end of the queue to become [1,2,4,5,6,7,8,3] and returns it.
23+
mRUQueue.fetch(5); // Moves the 5<sup>th</sup> element (6) to the end of the queue to become [1,2,4,5,7,8,3,6] and returns it.
24+
mRUQueue.fetch(2); // Moves the 2<sup>nd</sup> element (2) to the end of the queue to become [1,4,5,7,8,3,6,2] and returns it.
25+
mRUQueue.fetch(8); // The 8<sup>th</sup> element (2) is already at the end of the queue so just return it.
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= n &lt;= 2000</code></li>
33+
<li><code>1 &lt;= k &lt;= n</code></li>
34+
<li>At most <code>2000</code> calls will be made to <code>fetch</code>.</li>
35+
</ul>
36+
37+
<p>&nbsp;</p>
38+
<strong>Follow up:</strong> Finding an <code>O(n)</code> algorithm per <code>fetch</code> is a bit easy. Can you find an algorithm with a better complexity for each <code>fetch</code> call?
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time:
2+
# Constructor: O(n)
3+
# fetch: O(n)
4+
5+
class MRUQueue:
6+
7+
def __init__(self, n: int):
8+
self.queue = list(range(1, n + 1))
9+
10+
11+
def fetch(self, k: int) -> int:
12+
element = self.queue[k - 1]
13+
self.queue.pop(k - 1)
14+
self.queue.append(element)
15+
return element
16+
17+
18+
19+
20+
# Your MRUQueue object will be instantiated and called as such:
21+
# obj = MRUQueue(n)
22+
# param_1 = obj.fetch(k)

0 commit comments

Comments
 (0)