#1409
Medium Algorithms Queries on a permutation with key
Array Binary Indexed Tree Simulation
84.9% acceptance
Feb 25, 2026
514
645
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) 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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn process_queries(queries: Vec<i32>, m: i32) -> Vec<i32> {
let mut perm: Vec<i32> = (1..=m).collect();
let mut result = vec![];
for q in queries {
let pos = perm.iter().position(|&x| x == q).unwrap();
result.push(pos as i32);
perm.remove(pos);
perm.insert(0, q);
}
result
}
}