15% off all plans & roadmaps Use code

See plans

Design Most Recently Used Queue

Updated

TL;DR: You must support fetch(k), which moves the k-th element to the back of the queue and returns its value. Keep the queue in a list, remove the element at index k-1, append it to the end, and return it.

Problem

You are given an integer n that sets the size of a queue. The queue starts as [1, 2, ..., n] in increasing order. You need to design a data structure with one operation.

  • fetch(k): removes the k-th element (1-indexed) from the front of the queue, moves it to the end of the queue, and returns its value.

You implement the Most Recently Used Queue. It takes n at construction and handles many fetch(k) calls efficiently.

Example 1

Input: {"operations": ["MRUQueue", "fetch"], "parameters": [[1], [1]]}
Output: [null, 1]

Constraints

  • 1 <= n <= 2000
  • 1 <= k <= current queue size for each fetch(k) call
  • The number of fetch calls does not exceed 2000

Return the value of the fetched element for each fetch(k) call.

Constraints that matter

  • n and the number of fetches are both at most 2000, so an O(n) fetch costs about 4 million steps in total. That budget makes a list-based simulation fast enough.
  • The queue size never changes. Every fetch removes one element and adds one, so the size stays n. Each fetch works on at most n elements.
  • k is always between 1 and the current size. You never need to handle an out-of-range index, but you must convert the 1-based k to a 0-based index correctly.
  • Values are the integers 1 to n and are unique. Removing by value would also work, but removing by index is direct and avoids a search.

View on LeetCode

Hints

Hint 1

The queue is a sequence, and the operation reads an element by its position.

Hint 2

The naive approach reads the target value, then builds a new list.

Solution

Intuition

The queue is a sequence, and the operation reads an element by its position. Positions are easy to read from an array or list. The only changes are one removal in the middle and one append at the end. This is a design problem: you keep a sequence in a class and update it on each call.

Picture a line of people where the list is the line and each index is a person's spot in it. When fetch(k) calls the person at spot k, they step out, everyone behind them shuffles forward, and that person walks to the back.

What to notice is that you never search for a value. You get the position k directly, so you do not need a hash map. A plain list already gives O(1) reads by index and amortized O(1) appends at the end. The only costly step is the removal, which shifts every element after the removed one.

That shift costs O(n) per call, and the limits allow it. A list-based design is the right answer here. The rest of the page shows a rebuild-based brute force and then the in-place version you should write in an interview.

Watch the pattern animation

Worked example

Input: n = 1, then fetch(1)
Output: 1
Explanation: The queue starts as [1]. fetch(1) takes the first element, which is 1, moves it to the end, and returns 1. The queue stays [1], so the output is 1.

Approach 1: Brute force: rebuild the queue on every fetch

The naive approach reads the target value, then builds a new list. It copies every element except the target, in order, and appends the target at the end. Then it replaces the old list with the new one.

What's slow is the copying. Each fetch allocates a new list and copies n elements, even though only one element moves. That is wasted memory traffic and allocation work on every call.

The insight that fixes it is that the list can change in place. Removing one element at index k-1 shifts the tail left, and appending the value finishes the move. The rest of the order stays untouched, so no full copy is needed.

Steps

  1. Store the queue as a list that starts as 1 to n.
  2. On fetch(k), read the value at index k-1 and keep it in a variable.
  3. Create an empty new list. Copy every element whose index is not k-1, in order.
  4. Append the saved value to the new list.
  5. Replace the stored list with the new list and return the saved value.

Dry run

Use the example: n = 1, queue = [1].

  • Start: queue = [1].
  • fetch(1): value = queue[0] = 1.
  • Build next: skip index 0, so next = [].
  • Append value: next = [1].
  • Store next as the queue: queue = [1].
  • Return 1.

The output is 1, which matches the example.

Complexity

TimeO(n) per fetch
SpaceO(n)

Let n be the queue size. A fetch loops over all n indices once to copy the kept elements, which is n steps. Appending the value adds one more step, so each fetch does O(n) work. The new list holds n elements, so each fetch allocates O(n) space, and the old list is discarded.

PythonTested in our runner

from typing import List, Optional

class MRUQueue:
    def __init__(self, n: int):
        self.queue = list(range(1, n + 1))

    def fetch(self, k: int) -> int:
        value = self.queue[k - 1]
        # Build a new list without index k-1, then add the value at the end
        self.queue = self.queue[:k - 1] + self.queue[k:] + [value]
        return value

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: In-place remove and appendOptimalDesign (General/Specific)

The brute force copies all n elements on every call, but only one element changes position. What's slow is the full copy and the new allocation, which do far more work than the move needs.

The insight that fixes it is that the list already supports removal at an index. Removing index k-1 shifts the tail left by one slot. Appending the saved value at the end puts it in the right place. Two list operations replace the whole rebuild.

This version does the same O(n) shifting, but it skips the copy into a second list. It also keeps only one list alive, so memory stays at n elements.

Why it is correct. The list always holds the queue in its current order, from front to back. Removing index k-1 takes out exactly the k-th element, so the others keep their relative order. Appending the saved value then places it last, which matches the spec.

Steps

  1. Store the queue as a list that starts as 1 to n.
  2. On fetch(k), read the value at index k-1.
  3. Remove the element at index k-1 from the list. Later elements shift left by one.
  4. Append the saved value to the end of the list.
  5. Return the saved value.

Dry run

Use the example first, then a longer check.

Example: n = 1, queue = [1].

StepActionkQueue beforeValueQueue afterReturn
1Build queue from 1 to n-[]-[1]-
2Read index k-11[1]1[1]-
3Remove index 01[1]1[]-
4Append value1[]1[1]1

The last row returns 1, which matches the example.

Longer check: n = 4, queue = [1, 2, 3, 4]. fetch(3) reads 3, removes index 2, and leaves [1, 2, 4]. Appending 3 gives [1, 2, 4, 3]. fetch(2) then reads 2 and leaves [1, 4, 3, 2].

Complexity

TimeO(n) per fetch
SpaceO(n)

Let n be the queue size. Removing at index k-1 shifts up to n-1 elements left, which is O(n) work. Appending the value is amortized O(1), so one fetch costs O(n). The list holds n elements at all times, so the extra space beyond the stored queue is O(1).

PythonTested in our runner

from typing import List, Optional

class MRUQueue:
    def __init__(self, n: int):
        self.queue = list(range(1, n + 1))

    def fetch(self, k: int) -> int:
        # pop removes index k-1 and shifts later elements left
        value = self.queue.pop(k - 1)
        self.queue.append(value)
        return value

Common mistakes

  • value = self.queue[k] in place of queue[k - 1]. The input is 1-indexed, so this reads the next element and returns the wrong value.
  • return queue[k-1] without removing it. The element stays at its old position, so the order never changes.
  • Reading queue[k - 1] after the removal line. The removal shifts the next element into that slot, so the wrong value comes back. Save the value first.
  • Removing the element but forgetting the append. The size drops to n-1, and later calls with large k can read past the end.
  • Appending the value before removing index k-1 and then removing the wrong index. Either remove first, or remove index k after the append, but keep the two steps in one order.
  • In Go, reading this.queue[k-1] after append(this.queue[:k-1], this.queue[k:]...). The slice write can overwrite that slot, so copy the value into a variable first.

Edge cases

  • n = 1 with fetch(1). The queue stays [1] and the function returns 1.
  • fetch(1) on any queue. The front element moves to the back, so the queue rotates left by one.
  • fetch(size) on any queue. The last element is already at the back, so the order does not change and the last value is returned.
  • Repeated fetch(k) calls with the same k. The moved element lands at the back, so the next fetch(k) returns a different value unless k equals the size.
  • n = 2000 with 2000 fetch(1) calls. Each call shifts up to 1999 elements, about 4 million moves in total. This is within the limits.
  • fetch(2) on a queue of size 2, such as [1, 2]. The result is 2 and the queue becomes [1, 2].

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Design Most Recently Used Queue, with how to answer them.

Unlock the follow-ups

Design Most Recently Used Queue FAQ

What is the time complexity of Design Most Recently Used Queue?

Each fetch costs O(n) time, where n is the queue size. Removing the element at index k-1 shifts up to n-1 elements. The total time for Q fetches is O(Q * n).

Why use an in-place list for Design Most Recently Used Queue?

A list reads any position in O(1), which gives you the k-th element directly. Removing at an index and appending at the end are the only changes you need. Each fetch does one removal and one append, so the list fits the operation.

Can Design Most Recently Used Queue be solved in O(1) extra space?

Yes, the in-place version uses O(1) extra space beyond the stored queue. The queue itself needs O(n) space because it holds n values. The rebuild version needs O(n) extra space for each new list.

Why does a linked list not improve Design Most Recently Used Queue?

Removing a node is O(1) once you have it, but finding the k-th node needs a walk from the head. That walk costs O(k), so each fetch still costs O(n). A list is simpler and runs equally fast at these limits.

Is there a Python gotcha with this problem?

Yes, slicing like self.queue[:k - 1] + self.queue[k:] copies the whole list. That makes the rebuild version slower. Use pop and append to change the list in place.

Asked at

See which companies ask this — Pro

Practise it