You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.
Implement the BrowserHistory class:
BrowserHistory(string homepage) Initializes the object with the homepage of the browser.void visit(string url) Visits url from the current page. It clears up all the forward history.string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.Input:
["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"]
[["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:
1 <= homepage.length <= 201 <= url.length <= 201 <= steps <= 100homepage and url consist of '.' or lower case English letters.5000 calls will be made to visit, back, and forward.The most straightforward approach to manage browsing history is by using a list. Each time we visit a new URL, we can append it to the list from the current position, effectively simulating moving forward or backward in browser history.
current to track the index of the current web page.steps or until reaching the first page.steps or until reaching the last page.visit(): O(N) in the worst case (removing forward history), where N is the size of the current list.back() and forward(): O(1).To optimize the operations for forward and backward navigation, two stacks can be used:
visit, clear the forward stack and push the current page to the backward stack before visiting the new page.back, push the current page to the forward stack and pop from the backward stack.forward, pop from the forward stack and push to the backward stack.visit(): O(1). Adding to stack and clearing another.back() and forward(): O(steps). Maximum O(N) where N is the number of URLs.