914. Tab History

Medium3.5 points estimatedDesignStackDoubly-Linked List4 hints

Model the history of one browser tab as the class TabHistory. The constructor receives homepage, the page the tab starts on.

  • visit(url) opens url from the current page. All pages that were reachable with the forward button are forgotten.
  • back(steps) moves back by up to steps pages, stopping at the homepage if there are fewer pages behind. It returns the url of the page the tab ends on.
  • forward(steps) moves forward by up to steps pages, stopping at the newest remaining page, and returns the url you end on.

Visiting a url that equals the current page still creates a new history entry. Every call must run in O(1) time, even when steps is huge.

Example 1

Input:
operations = ["TabHistory","visit","visit","back","visit","forward","back","forward"]arguments = [["start.page"],["maps.example"],["mail.example"],[1],["news.example"],[3],[5],[1]]
Output:
[null,null,null,"maps.example",null,"news.example","start.page","maps.example"]
Explanation:

After visiting maps and mail, going back one step shows maps. Visiting news from there discards mail, so forward cannot move further and stays on news. Going back far stops at the homepage, and forward 1 returns to maps.

Example 2

Input:
operations = ["TabHistory","back","forward"]arguments = [["a.io"],[4],[2]]
Output:
[null,"a.io","a.io"]
Explanation:

With no other page visited the tab cannot move in either direction, so both calls return the homepage.

Constraints

1 ≤ homepage.length, url.length ≤ 20

1 ≤ steps ≤ 109

At most 20000 calls in total

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Input
Each case is an operation log. operations names the class first and then each method call; arguments holds the arguments for each, in the same order. Your answer is one list with a result per operation - null for the constructor and for methods that return nothing.

Expected complexity

Time
O(1) per call
Space
O(number of visits)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…

operations names the class, then each method to call; arguments holds one list of arguments per operation, in the same order.