Queries on a Permutation With Key Problem
#1409
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1409.
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
- In the beginning, you have the permutation
P=[1,2,3,...,m]. - For the current
i, find the position ofqueries[i]in the permutationP(indexing from 0) and then move this at the beginning of the permutationP. Notice that the position ofqueries[i]inPis the result forqueries[i].
Return an array containing the result for the given queries.
Example 1:
Input: queries = [3,1,2,1], m = 5
Output: [2,1,2,1]
Explanation: The queries are processed as follow:
For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5].
For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5].
For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5].
For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5].
Therefore, the array containing the result is [2,1,2,1].
Example 2:
Input: queries = [4,1,2,2], m = 4
Output: [3,1,2,0]
Example 3:
Input: queries = [7,5,5,8,3], m = 8
Output: [6,5,0,7,5]
Constraints:
1 <= m <= 10^31 <= queries.length <= m1 <= queries[i] <= m
Solution
Approach: Simulation
With m <= 1000, we can just keep the permutation P in an array and do what the statement says.
For each query q:
- Find the index
iofqinPby scanning it. That index is the answer for this query. - Move
qto the front: shiftP[0..i-1]one place to the right, then putqatP[0].
Each query scans and shifts at most m elements, which is fast enough here. (A Fenwick tree over m + queries.length slots can bring this down to O(log m) per query, but it is not needed for these limits.)
Complexity: O(q · m) time for q queries, and O(m) space for the permutation.
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
p = list(range(1, m + 1))
ans = []
for q in queries:
i = p.index(q)
ans.append(i)
p.pop(i)
p.insert(0, q) # move q to the front
return ans