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

Reprinted from:

Author: etworker
Link: https://leetcode-cn.com/probl…
Source: leetcode
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.

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

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

    def add(self, i, x):
        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):
            fenw.add(i + m, 1)
            vimap[i] = i + m

        # - next head position
        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--
            fenw.add(i, -1)

            # - all elements value shift +1
            fenw.add(cur, 1)

            # - move next head position to left
            cur -= 1
            
        return ans