Problem Description
Given an initial order of n windows represented by an array (where the first element is at the top) and a list of queries where each query brings the corresponding window to the top, simulate the alt+tab behavior and return the final state of the window order.
Key Insights
- Every query “brings a window to the top” by removing it from its current position and reinserting it at the beginning.
- If a window is queried more than once, only its most recent move matters since it ends up higher than its previous positions.
- The windows that never appear in queries remain in their initial order and are placed below the windows that were queried.
- Instead of simulating each move explicitly—which could be expensive—we can track the last query index (timestamp) for each window and then reconstruct the final ordering.
Space and Time Complexity
Time Complexity: O(n + m + k log k) where n = number of windows, m = number of queries, and k = number of unique queries (k ≤ n).
Space Complexity: O(n) for the dictionary and the resulting arrays.
Solution
We can optimize the simulation by avoiding expensive removals in the list. The idea is to record the last occurrence (timestamp) of each window in the queries. For every window that appears in the queries, its final position is entirely determined by the time it was last queried—the later the query, the closer to the top. All windows that were never moved remain in their original order and are placed below the moved windows.
The steps are:
- Iterate over queries and store the index (timestamp) for each window’s most recent query.
- For windows that have been queried, collect their (timestamp, window) pairs and sort them in descending order.
- Build the final ordering as the sorted queried windows (in the order determined by their last query) followed by the windows that were never queried (preserving their initial order).