Queries on a Permutation With Key - Problem
Given an array queries of positive integers between 1 and m, you need to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
Initial Setup: You start with the permutation P = [1, 2, 3, ..., m].
Processing Rule: For the current query queries[i]:
- Find the position of
queries[i]in the permutationP(indexing from 0) - Move this element to the beginning of the permutation
P - The position found is the result for
queries[i]
Return an array containing the result for all given queries.
Input & Output
Example 1 — Basic Case
$
Input:
queries = [3,1,2,1], m = 5
›
Output:
[2,1,1,0]
💡 Note:
Start: P=[1,2,3,4,5]. Query 3: position 2, P=[3,1,2,4,5]. Query 1: position 1, P=[1,3,2,4,5]. Query 2: position 2, P=[2,1,3,4,5]. Query 1: position 1, P=[1,2,3,4,5].
Example 2 — Single Query
$
Input:
queries = [4], m = 4
›
Output:
[3]
💡 Note:
Start: P=[1,2,3,4]. Query 4: position 3, P=[4,1,2,3]. Result is [3].
Example 3 — Repeated First Element
$
Input:
queries = [1,1,1], m = 3
›
Output:
[0,0,0]
💡 Note:
Start: P=[1,2,3]. All queries ask for element 1 which is always at position 0 after first query.
Constraints
- 1 ≤ queries.length, m ≤ 103
- 1 ≤ queries[i] ≤ m
Visualization
Tap to expand
Understanding the Visualization
1
Input
queries = [3,1,2,1], m = 5
2
Process
For each query, find position then move to front
3
Output
Array of positions: [2,1,1,0]
Key Takeaway
🎯 Key Insight: Each query returns the current position of the element, then moves it to the front, shifting all elements that were before it one position to the right.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code