Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Queries on a Permutation With Key

XPChallenge Points: 20
levelLevel: Medium

You are given a list of queries, each containing numbers between 1 and m.
Initially, you create a permutation P = [1, 2, 3, ..., m].

For each query value:

  • Look for its current index (0-based) inside P.

  • That index becomes the answer for this query.

  • Then remove that number from its position in P and insert it at the front.

After processing all queries one-by-one, return an array of all recorded indices.

This simulates repeatedly bringing requested elements to the beginning of the permutation.

Example 1:

Input: queries = [2,4,2,5], m = 5

Output: [1, 3, 1, 4]

Explanation:

Start: P = [1,2,3,4,5] Query 2 → index 1, P becomes [2,1,3,4,5] Query 4 → index 3, P becomes [4,2,1,3,5] Query 2 → index 0, P becomes [2,4,1,3,5] Query 5 → index 3, P becomes [5,2,4,1,3]

Example 2:

Input: queries = [1,1,3], m = 4

Output: [0, 0, 2]

Explanation:

Start: [1,2,3,4] 1 → index 0, after move remains [1,2,3,4] 1 → index 0 3 → index 2, P becomes [3,1,2,4]

Example 3:

Input: queries = [6,3,1,6], m = 6

Output: [5, 3, 2, 2]

Explanation:

Start: [1,2,3,4,5,6] 6 → index 5, move → [6,1,2,3,4,5] 3 → index 3, move → [3,6,1,2,4,5] 1 → index 2, move → [1,3,6,2,4,5] 6 → index 2, move → [6,1,3,2,4,5]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result