Problem
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 thehomepage
of the browser.void visit(string url)
Visitsurl
from the current page. It clears up all the forward history.string back(int steps)
Movesteps
back in history. If you can only returnx
steps in the history andsteps > x
, you will return onlyx
steps. Return the currenturl
after moving back in history at moststeps
.string forward(int steps)
Movesteps
forward in history. If you can only forwardx
steps in the history andsteps > x
, you will forward onlyx
steps. Return the currenturl
after forwarding in history at moststeps
.
Examples
Example:
|
|
Solution
Method 1 – Array with Pointer
Intuition
To efficiently manage browser history, we use a list to store visited URLs and a pointer to track the current page. When visiting a new URL, we remove all forward history and add the new URL. The pointer always indicates the current page, allowing quick back and forward navigation.
Approach
- Use a list to store the history of URLs.
- Maintain an integer pointer for the current position in history.
- On visit, remove all URLs after the current pointer and append the new URL.
- On back, move the pointer left by up to
steps
, but not past the first URL. - On forward, move the pointer right by up to
steps
, but not past the last URL. - Return the URL at the current pointer after each operation.
Complexity
- ⏰ Time complexity:
O(1)
for visit, back, and forward, as all operations are direct list and pointer manipulations. - 🧺 Space complexity:
O(n)
, where n is the number of visited URLs.
Code
|
|
|
|
|
|