Problem Statement
Design a Tab Handler (like a browser's tab manager) that supports:
- openTab(url) — Open a new tab with the given URL, assign a unique ID
- openTab(url, force) — Open a tab even if another tab already has the same URL
- closeCurrentTab() — Close the currently active tab
- closeTab(id) — Close a tab by its unique ID
- getCurrentTab() — Return the currently active tab
- listTabs() — List all currently open tabs in order
Aim for efficient operations (O(1) where possible).
Constraints
- Each tab has a unique auto-incrementing ID
- Tabs maintain their open order
- Closing the current tab should activate an adjacent tab
- At most
10^5operations
Example
openTab("google.com") → id=1, current=1
openTab("github.com") → id=2, current=2
openTab("google.com") → duplicate URL, no new tab (unless forced)
openTab("google.com", true) → id=3, current=3 (forced)
getCurrentTab() → tab 3
closeTab(2) → removes github tab
listTabs() → [google(1), google(3)]
What the Interviewer Expects
- HashMap + Doubly Linked List — the ideal combo:
HashMap<int, Node>: ID → tab node for O(1) lookup by ID- Doubly Linked List: maintains tab order + current pointer, O(1) insert/delete
- Node structure — each node holds
id,url,prev,next. - Duplicate URL handling — without
force, check if URL already open (may need a URL→node index). Withforce, always create new. - Current tab pointer — track which node is active. On close, move to prev or next.
- This combines data-structure selection with API design — not a pure algorithm problem. Show clean interface design.
Follow-ups
- How would you add "reopen last closed tab" (undo)?
- How would you implement tab history (back/forward within a tab)?
- How would you handle tab groups or pinned tabs?
- What if you needed to find a tab by URL in O(1)? What structure would you add?