LeetCode 1409: Queries on a Permutation With Key Solution

Master LeetCode problem 1409 (Queries on a Permutation With Key), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1409. Queries on a Permutation With Key

Problem Explanation

Explanation

We can simulate the process described in the problem statement. For each query, we find the index of the query value in the current permutation and move that value to the beginning of the permutation. We can use a list to represent the permutation and update it accordingly for each query.

Time Complexity: O(m * n) where n is the number of queries and m is the maximum value in queries.
Space Complexity: O(m) where m is the maximum value in queries.

Solution Code

class Solution {
    public int[] processQueries(int[] queries, int m) {
        List<Integer> permutation = new ArrayList<>();
        for (int i = 1; i <= m; i++) {
            permutation.add(i);
        }
        
        int[] result = new int[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int query = queries[i];
            int index = permutation.indexOf(query);
            result[i] = index;
            permutation.remove(index);
            permutation.add(0, query);
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1409 (Queries on a Permutation With Key)?

This page provides optimized solutions for LeetCode problem 1409 (Queries on a Permutation With Key) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1409 (Queries on a Permutation With Key)?

The time complexity for LeetCode 1409 (Queries on a Permutation With Key) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1409 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1409 in Java, C++, or Python.

Back to LeetCode Solutions