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 permutation P (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,2,1]
💡 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
Queries on a Permutation With Key INPUT Initial P = [1,2,3,4,5] 1 2 3 4 5 idx 0 idx 1 idx 2 idx 3 idx 4 queries = [3,1,2,1] 3 1 2 1 m = 5 Position Map (Initial) 1 --> pos 0 2 --> pos 1 3 --> pos 2 4 --> pos 3 5 --> pos 4 ALGORITHM STEPS 1 Query 3: Find pos of 3 P=[1,2,3,4,5] pos=2 Move 3 to front P=[3,1,2,4,5] ans=2 2 Query 1: Find pos of 1 P=[3,1,2,4,5] pos=1 Move 1 to front P=[1,3,2,4,5] ans=1 3 Query 2: Find pos of 2 P=[1,3,2,4,5] pos=2 Move 2 to front P=[2,1,3,4,5] ans=1 4 Query 1: Find pos of 1 P=[2,1,3,4,5] pos=1 Move 1 to front P=[1,2,3,4,5] ans=0 Position Map Tracking: Update positions for elements shifted when moving to front FINAL RESULT Output Array 2 1 1 0 Position Results: Query 3 --> Position 2 Query 1 --> Position 1 Query 2 --> Position 1 Query 1 --> Position 0 Final P State: 1 2 3 4 5 OK Result Verified Key Insight: Use a HashMap to track each element's current position in the permutation. When processing a query: 1) Look up the position instantly using the map (O(1) lookup) 2) Update positions: queried element goes to 0, others between 0 and old position shift right by 1 TutorialsPoint - Queries on a Permutation With Key | Position Tracking with Map Approach
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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