Skip to the code
cf.
+25 XP

#695 Tab Limit That Closes the Stalest Tab

medium

A browser extension limits you to limit open tabs. Opening a new tab when the limit is reached closes the tab you used least recently. Write a class TabLimiter:

  • new TabLimiter(limit) starts with no tabs.
  • open(tab) opens tab (or, if it's already open, just uses it). Returns the id of the tab closed to make room, or -1 if none was closed.
  • focus(tab) uses tab and returns true if it is open, or returns false if it isn't (nothing changes then).
  • list() returns the open tabs from most recently used to least recently used.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new TabLimiter(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["TabLimiter","open","open","open","focus","open","list"]
[[3],[1],[2],[3],[1],[4],[]]
Output: [null,-1,-1,-1,true,2,[4,1,3]]

Focusing tab 1 makes tab 2 the stalest, so opening tab 4 closes tab 2.

Example 2

Input: ["TabLimiter","focus","list"]
[[2],[9],[]]
Output: [null,false,[]]

Tab 9 was never opened.

Constraints

  • 1 <= limit <= 1000
  • 1 <= tab <= 10^6
  • At most 10^4 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).