Queries on a Permutation With Key

Given the array queries of positive integers between 1 and m, 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 of queries[i] in the permutation P (indexing from 0) and then move this value to the beginning of the permutation P.
  • The position of queries[i] in P is the result for queries[i].

Return an array containing the result for the given queries.

Example 1
Inputqueries = [3,1,2,1], m = 5
Output[2,1,2,1]
Processing the queries moves each queried value to the front of P, producing positions [2, 1, 2, 1].
Example 2
Inputqueries = [4,1,2,2], m = 4
Output[3,1,2,0]
After each query is located and moved to the beginning of P, the recorded positions are [3, 1, 2, 0].

Constraints

  • 1 <= m <= 10^3
  • 1 <= queries.length <= m
  • 1 <= queries[i] <= m

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate