3237. Alt and Tab Simulation π
Description
There are n
windows open numbered from 1
to n
, we want to simulate using alt + tab to navigate between the windows.
You are given an array windows
which contains the initial order of the windows (the first element is at the top and the last one is at the bottom).
You are also given an array queries
where for each query, the window queries[i]
is brought to the top.
Return the final state of the array windows
.
Example 1:
Input: windows = [1,2,3], queries = [3,3,2]
Output: [2,3,1]
Explanation:
Here is the window array after each query:
- Initial order:
[1,2,3]
- After the first query:
[3,1,2]
- After the second query:
[3,1,2]
- After the last query:
[2,3,1]
Example 2:
Input: windows = [1,4,2,3], queries = [4,1,3]
Output: [3,1,4,2]
Explanation:
Here is the window array after each query:
- Initial order:
[1,4,2,3]
- After the first query:
[4,1,2,3]
- After the second query:
[1,4,2,3]
- After the last query:
[3,1,4,2]
Constraints:
1 <= n == windows.length <= 105
windows
is a permutation of[1, n]
.1 <= queries.length <= 105
1 <= queries[i] <= n
Solutions
Solution 1: Hash Table + Reverse Traversal
According to the problem description, the later the query, the earlier it appears in the result. Therefore, we can traverse the $\textit{queries}$ array in reverse order, using a hash table $\textit{s}$ to record the windows that have already appeared. For each query, if the current window is not in the hash table, we add it to the answer array and also add it to the hash table. Finally, we traverse the $\textit{windows}$ array again, adding the windows that are not in the hash table to the answer array.
The time complexity is $O(n + m)$, and the space complexity is $O(m)$. Here, $n$ and $m$ are the lengths of the $\textit{windows}$ and $\textit{queries}$ arrays, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|