#1409
Queries on a Permutation With Key
MediumArrayBinary Indexed TreeSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a HashMap to keep track of the indices of elements in the permutation, allowing us to find and move elements in constant time. This significantly reduces the number of operations needed.
⚙️
Algorithm
3 steps- 1Step 1: Initialize the permutation P as a list from 1 to m and create a HashMap to store the current indices of each element.
- 2Step 2: For each query, use the HashMap to find the index of the query in constant time.
- 3Step 3: Move the queried element to the front of the permutation and update the indices in the HashMap accordingly.
solution.py12 lines
1def processQueries(queries, m):
2 P = list(range(1, m + 1))
3 index_map = {val: idx for idx, val in enumerate(P)}
4 result = []
5 for query in queries:
6 index = index_map[query]
7 result.append(index)
8 # Move the queried element to the front
9 P.insert(0, P.pop(index))
10 # Update the index map
11 for i in range(len(P)): index_map[P[i]] = i
12 return resultℹ
Complexity note: The time complexity is O(n) for each query due to the efficient use of a HashMap to track indices, and the space complexity is O(n) for storing the permutation and the index map.
- 1Using a HashMap can significantly reduce the time complexity of finding indices.
- 2Moving elements in an array can be optimized by maintaining a mapping of indices.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.