Alt and Tab Simulation - Problem

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 after all queries are processed.

Input & Output

Example 1 — Basic Alt+Tab Simulation
$ Input: windows = [1,2,3], queries = [3,1,3]
Output: [3,1,2]
💡 Note: Start with [1,2,3]. Query 3 moves it to front: [3,1,2]. Query 1 moves it to front: [1,3,2]. Query 3 moves it to front: [3,1,2].
Example 2 — Single Query
$ Input: windows = [1,2,3,4,5], queries = [4]
Output: [4,1,2,3,5]
💡 Note: Only window 4 is queried, so it moves to the front while others maintain their relative order.
Example 3 — Multiple Same Queries
$ Input: windows = [2,1,3], queries = [1,1,1]
Output: [1,2,3]
💡 Note: Window 1 is brought to front on first query [1,2,3], subsequent queries of same window don't change the order.

Constraints

  • 1 ≤ windows.length ≤ 103
  • 1 ≤ queries.length ≤ 105
  • 1 ≤ windows[i], queries[i] ≤ 106
  • All elements in windows are unique
  • All queries[i] exist in windows

Visualization

Tap to expand
Alt + Tab Simulation INPUT Initial Window Stack Window 1 (Top) Window 2 Window 3 (Bottom) windows array: 1 2 3 queries array: 3 1 3 [3,1,3] = Alt+Tab sequence ALGORITHM STEPS 1 Initialize HashMap Track window positions pos: {1:0, 2:1, 3:2} 2 Query 3: Bring to top Stack: [3,1,2] pos: {3:0, 1:1, 2:2} 3 Query 1: Bring to top Stack: [1,3,2] pos: {1:0, 3:1, 2:2} 4 Query 3: Bring to top Stack: [3,1,2] pos: {3:0, 1:1, 2:2} HashMap tracks O(1) lookups FINAL RESULT Final Window Stack Window 3 (Top) Window 1 Window 2 (Bottom) Output Array: 3 1 2 [0] [1] [2] OK - Done! Result: [3, 1, 2] Key Insight: Use a HashMap to track each window's position for O(1) lookup. When a window is queried, remove it from current position and insert at index 0. Update all affected positions in the map. Time Complexity: O(n*m) where n = windows, m = queries. Space: O(n) for the HashMap. TutorialsPoint - Alt and Tab Simulation | Hash Map with Position Tracking
Asked in
Microsoft 35 Google 28 Apple 22
23.4K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen