DEV Community

SalahElhossiny
SalahElhossiny

Posted on

3 2

Leetcode Solutions: Queries on a Permutation With Key

Given the array queries of positive integers between 1 and m, you have to process all queriesi 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.

class Solution:
    def processQueries(self, queries: List[int], m: int) -> List[int]:

        P, result = list(range(1, m + 1)), []

        for q in queries:

            index = P.index(q)

            result.append(index)

            P = [P.pop(index)] + P

        return result


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay