
Sponsored
Sponsored
This approach involves using a list (or similar data structure) to keep track of the pages visited. We use an index to keep track of the current page. Visiting a new page from the current page will truncate the list beyond the current index before adding the new page. Moving back or forward adjusts the index within the bounds of the list.
Time Complexity: Each operation (visit, back, forward) is O(1) on average due to direct index manipulation or list slicing.
Space Complexity: O(n), where n is the number of URLs stored in history.
1class BrowserHistory {
2 constructor(homepage) {
3 this.history = [homepage];
4 this.current = 0;
5 }
6
7 visit(url) {
8 this.history = this.history.slice(0, this.current + 1);
9 this.history.push(url);
10 this.current++;
11 }
12
13 back(steps) {
14 this.current = Math.max(0, this.current - steps);
15 return this.history[this.current];
16 }
17
18 forward(steps) {
19 this.current = Math.min(this.history.length - 1, this.current + steps);
20 return this.history[this.current];
21 }
22}For JavaScript, we use an array 'history' to manage the URLs and 'current' for the index. Methods utilize JavaScript array slicing and math functions to seamlessly implement 'visit', 'back', and 'forward'.
This approach uses two stacks: one to store backward paths and another to store forward paths. The current page is not stored in the stack, but rather observed as the topmost element of the backward stack. The back function pops elements from the backward stack to the forward stack as necessary, and the forward function performs the opposite action. This effectively mimicks the process of moving through the history as we go back and forth.
Time Complexity: Each call to visit, back, or forward is O(steps) due to operations over respective stacks.
Space Complexity: O(n) for maintaining stacks with n pages.
In JavaScript, two arrays serve as stacks. When visiting a new site, the forward history is cleared. The back and forward methods modify these stacks to simulate historical navigation.