MediumArrayLinked ListStackDesignDoubly-Linked List

Design Browser History

1 approach, code in every language

Problem description

Model the history of a single browser tab that starts on a given homepage. As the user browses, you must support moving to new pages as well as stepping backward and forward through previously seen pages.

Implement the class BrowserHistory. The constructor receives the homepage string and opens the tab on that page. visit(url) navigates to url from the current page, which clears every page that was ahead in the forward history. back(steps) moves back at most steps pages, stopping at the oldest page if there are not enough, and returns the resulting url. forward(steps) moves forward at most steps pages, stopping at the newest page if there are not enough, and returns the resulting url.

Example 1

Input: operations = ["BrowserHistory", "visit", "visit", "visit", "back", "back", "forward", "visit", "forward", "back", "back"] args = [["leetcode.com"], ["google.com"], ["facebook.com"], ["youtube.com"], [1], [1], [1], ["linkedin.com"], [2], [2], [7]]

Output: [null, null, null, null, "facebook.com", "google.com", "facebook.com", null, "linkedin.com", "google.com", "leetcode.com"]

After visiting three sites, back(1) lands on facebook.com and back(1) again on google.com. forward(1) returns to facebook.com. Visiting linkedin.com erases the forward pages, so forward(2) cannot advance and stays on linkedin.com; back(2) reaches google.com and back(7) clamps to leetcode.com.

Example 2

Input: operations = ["BrowserHistory", "back", "forward", "visit"] args = [["a.com"], [3], [2], ["b.com"]]

Output: [null, "a.com", "a.com", null]

With only the homepage present, back and forward both clamp to a.com. Visiting b.com then moves the current page forward to b.com.

Constraints

  • 1 <= homepage.length <= 20 and 1 <= url.length <= 20
  • 1 <= steps <= 100
  • At most 5 * 10^4 total calls will be made to visit, back, and forward.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free