Queries on a Permutation With Key - Problem

Imagine you have a special list that starts as [1, 2, 3, ..., m] - a perfect sequence from 1 to m. Now, you're given a series of queries, and for each query, you need to:

  1. Find where the queried number currently sits in your list (this position is your answer!)
  2. Move that number to the front of the list, shifting everything else to the right

This creates a dynamic reordering system where frequently queried numbers bubble up to the front, similar to how a browser's history works or how an operating system manages recently used files.

Goal: Return an array containing the position (0-indexed) where each queried number was found before moving it to the front.

Example: If you start with [1,2,3,4,5] and query 3, you'll find it at position 2, then your list becomes [3,1,2,4,5].

Input & Output

example_1.py — Basic Example
$ Input: queries = [3,1,2,1], m = 5
Output: [2,1,1,1]
💡 Note: Starting with [1,2,3,4,5]: Query 3→found at index 2, becomes [3,1,2,4,5]. Query 1→found at index 1, becomes [1,3,2,4,5]. Query 2→found at index 2, becomes [2,1,3,4,5]. Query 1→found at index 1, becomes [1,2,3,4,5].
example_2.py — Single Query
$ Input: queries = [4], m = 4
Output: [3]
💡 Note: Starting with [1,2,3,4]: Query 4 is found at index 3, so we return [3]. The array becomes [4,1,2,3].
example_3.py — Repeated Same Query
$ Input: queries = [2,2,2], m = 3
Output: [1,0,0]
💡 Note: Starting with [1,2,3]: First query 2→found at index 1, becomes [2,1,3]. Second query 2→found at index 0, stays [2,1,3]. Third query 2→found at index 0, stays [2,1,3].

Constraints

  • 1 ≤ queries.length ≤ 2×104
  • 1 ≤ queries[i] ≤ m
  • 1 ≤ m ≤ 103
  • All elements in queries are valid indices (between 1 and m inclusive)

Visualization

Tap to expand
Queries on Permutation VisualizationStep 1: Initial State12345Step 2: Query 3 (found at index 2)31245Step 3: Query 1 (found at index 1)13245Results:Query 3 → Position 2Query 1 → Position 1Query 2 → Position 2Query 1 → Position 1Answer: [2,1,1,1]
Understanding the Visualization
1
Initialize
Start with ordered list [1,2,3,4,5]
2
Query 3
Find 3 at position 2, record answer, move to front
3
Query 1
Find 1 at position 1 in new list [3,1,2,4,5], move to front
4
Pattern
Recently queried elements stay near the front, affecting future query positions
Key Takeaway
🎯 Key Insight: This is essentially a move-to-front transform where each access moves an element to position 0, creating a self-organizing list where frequently accessed items naturally migrate toward the front.
Asked in
Amazon 25 Google 20 Microsoft 15 Meta 12
28.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen