Design Browser System With LRU Tabs
Design a browser system that can keep at most N tabs open. Whenever a new tab is opened while N tabs are already open, automatically close the least recently used tab.
Method Signatures
Create Browser System
BrowserSystem(int maxTabs)
- Creates a browser system with no open tabs.
maxTabs specifies the maximum number of tabs that can remain open.
Open a Tab
String openTab(String tabId)
- Opens the tab identified by
tabId.
- The newly opened tab becomes the most recently used tab.
- If
tabId is already open, do not create another copy. Instead, mark the existing tab as the most recently used tab.
- If
maxTabs tabs are already open and a different tab is opened, close the least recently used tab.
- Return the identifier of the tab that was closed.
- Return an empty string if no tab was closed.
Use an Open Tab
boolean useTab(String tabId)
- If the specified tab is open, mark it as the most recently used tab and return
true.
- Return
false if the specified tab is not open.
Get Open Tabs
List<String> getOpenTabs()
- Return the identifiers of all currently open tabs.
- Return them from the least recently used tab to the most recently used tab.
- Return an empty list when no tabs are open.
LRU Rules
- Opening a new tab makes it the most recently used tab.
- Opening an already open tab makes that tab the most recently used.
- Successfully using an open tab makes it the most recently used.
- When removal is required, close exactly one tab: the tab at the least-recently-used position.
- The number of open tabs must never exceed
maxTabs.
Constraints
1 ≤ maxTabs ≤ 100
1 ≤ tabId.length() ≤ 100
tabId contains printable characters.
- At most
100,000 method calls will be made after creating the browser system.
- Tab identifier comparisons are case-sensitive.
tabId is never an empty string.
Examples
Example 1
BrowserSystem(maxTabs = 3)
Output: Browser system created
openTab(tabId = "news")
Output: ""
openTab(tabId = "mail")
Output: ""
openTab(tabId = "music")
Output: ""
useTab(tabId = "news")
Output: true
openTab(tabId = "sports")
Output: "mail"
getOpenTabs()
Output: ["music", "news", "sports"]
The "news" tab becomes the most recently used when it is accessed. Therefore, "mail" is closed when "sports" is opened.
Example 2
BrowserSystem(maxTabs = 2)
Output: Browser system created
openTab(tabId = "store")
Output: ""
openTab(tabId = "search")
Output: ""
openTab(tabId = "store")
Output: ""
openTab(tabId = "video")
Output: "search"
useTab(tabId = "search")
Output: false
getOpenTabs()
Output: ["store", "video"]
Reopening "store" makes it the most recently used tab without creating a duplicate. Therefore, "search" is closed when "video" is opened.