[Leet Code] Queries on a Permutation With Key

Leet Code: https://leetcode.com/problems/queries-on-a-permutation-with-key/

Problem:

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 of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i].Return an array containing the result for the given queries.

Example:

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].

Solution:

class Solution(object):
def processQueries(self, queries, m):
"""
:type queries: List[int]
:type m: int
:rtype: List[int]
"""
answer = queries
p = [number for number in range(1,m+1)]
for i, v in enumerate(queries):
answer[i] = p.index(v)
p.remove(v)
p.insert(0,v)
return answer

So first we assign the list queries to a variable answer, this will give us the same length of list. Then we create the p variable of 1-m(m+1 is needed because arrays start at 0). Then we use the enumerate function in python, the i will provide us the index, and v will provide us the value of queries at that index. Then we assign the first each index of answer to the position of the index of the value in query. Then we remove the value in p and insert it back at the start. Then return our answer.

--

--

Learning, and posting my findings!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store