Similar Problems
Similar Problems not available
Queries On A Permutation With Key - Leetcode Solution
Companies:
LeetCode: Queries On A Permutation With Key Leetcode Solution
Difficulty: Medium
Topics: array simulation
The Queries on a Permutation with Key problem on LeetCode asks us to implement a class called Solution
that has the following two methods:
void processQueries(vector<int>& queries, int m)
: This method takes in a vector of integers calledqueries
and an integer calledm
. It should process each query in thequeries
vector as follows:- Given the permutation of the integers
1
tom
asp = [1, 2, ..., m]
, find the index of the query element inp
. - Remove the query element from
p
and insert it at the front ofp
. - Push the index of the query element into a result vector.
- Given the permutation of the integers
vector<int> processQueries(vector<int>& queries, int m)
: This method should return the result vector.
Here's a step-by-step solution to this problem:
- Implement a class called
Solution
that contains an integer vector calledp
to represent the permutation of numbers1
tom
, and an integer vector calledresult
to store the results of processing each query.
class Solution {
private:
vector<int> p;
vector<int> result;
public:
Solution(){}
};
- Implement the
processQueries
method by first initializing the permutationp
with the numbers1
tom
.
void processQueries(vector<int>& queries, int m) {
// Initialize p with numbers 1 to m
for(int i=1; i<=m; i++){
p.push_back(i);
}
}
- Loop through the
queries
vector and for each query:- Find the index of the query element in
p
- Remove the query element from
p
usingerase
method and insert it at the front usinginsert
method. - Push the index of the query element into the
result
vector.
- Find the index of the query element in
void processQueries(vector<int>& queries, int m) {
for(int i=1; i<=m; i++){
p.push_back(i);
}
for(int i=0; i<queries.size(); i++){
int idx = find(p.begin(), p.end(), queries[i]) - p.begin();
result.push_back(idx);
p.erase(p.begin() + idx);
p.insert(p.begin(), queries[i]);
}
}
- Implement the
getResults
method to return the result vector.
vector<int> getResults(){
return result;
}
The complete solution of the Queries on a Permutation with Key problem on LeetCode:
class Solution {
private:
vector<int> p;
vector<int> result;
public:
Solution(){}
void processQueries(vector<int>& queries, int m) {
for(int i=1; i<=m; i++){
p.push_back(i);
}
for(int i=0; i<queries.size(); i++){
int idx = find(p.begin(), p.end(), queries[i]) - p.begin();
result.push_back(idx);
p.erase(p.begin() + idx);
p.insert(p.begin(), queries[i]);
}
}
vector<int> getResults(){
return result;
}
};
Queries On A Permutation With Key Solution Code
1