# Leetcode 1409. Query keyed permutation – Python

Time：2021-7-27

1409. Query keyed arrangement

Three solutions

## Solution I violence

``````class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
m = min(m, max(queries))
p = [i+1 for i in range(m)]
ans = []
for x in queries:
i = p.index(x)
ans.append(i)
x = p.pop(i)
p.insert(0, x)
return ans``````

## Solution two deque

``````# from collections import deque
class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
d = deque([i + 1 for i in range(min(m, max(queries)))])
ans = []
for q in queries:
i = d.index(q)
ans.append(i)
d.remove(q)
d.appendleft(q)
return ans``````

## Three tree array

Author: etworker
Source: leetcode

``````class Fenwick:
def __init__(self, n):
sz = 1
while sz <= n:
sz *= 2
self.size = sz
self.data =  * sz

def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s

while i < self.size:
self.data[i] += x
i += i & -i

class Solution:
def processQueries(self, queries: List[int], m: int) -> List[int]:
# - because queries.length <= m, so use double space
fenw = Fenwick(2 * m)

# - vimap keeps the position of value i
vimap = {}
for i in range(1, m + 1):
vimap[i] = i + m

cur = m

ans = []
for q in queries:
# - get current position of value q
i = vimap.pop(q)

# - rank means index
rank = fenw.sum(i-1)
ans.append(rank)

# - move q to the head position
vimap[q] = cur

# - all elements behind position i will move left, so rank--

# - all elements value shift +1