Design Browser History

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

Design a browser history tracker that supports visiting URLs, going back, and going forward.

Implement a function that processes an array of operations and an array of arguments:

  • "BrowserHistory" — Initializes the browser with homepage as the current page.
  • "visit" — Visits url from the current page. This clears all forward history.
  • "back" — Moves steps back in history. Returns the current URL after moving (stops at the homepage if steps exceeds history).
  • "forward" — Moves steps forward in history. Returns the current URL after moving (stops at the most recent page if steps exceeds forward history).

Examples

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"]

Explanation: Start at leetcode.com. Visit google, facebook, youtube. back(1)→facebook, back(1)→google, forward(1)→facebook. Visit linkedin (clears youtube). forward(2)→linkedin (no more forward). back(2)→google. back(7)→leetcode.

Example 2:

Input: operations = ["BrowserHistory","visit","back","forward"], args = [["home.com"],["page.com"],[5],[5]]

Output: [null,null,"home.com","page.com"]

Explanation: Visit page.com. back(5) stops at home.com. forward(5) stops at page.com.

Constraints

  • 1 <= homepage.length, url.length <= 20
  • 1 <= steps <= 100
  • At most 5000 calls to visit, back, and forward
Source: Custom Data Structures pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle