Member-only story
Leetcode 1472: Design Browser
2 min readJun 12, 2020
In this Leetcode problem, we try to design a simple code browser with 3 methods: visit, back, forward
.
Additionally, it says the number of calls will be at most 5000
, which is why I set the history size to 5001
(5000 calls plus homepage).
Solution
- We are going to use a simple array
String[]
as history - The reason to use an array instead of 2 stacks or a doubly lined list is that we can access many steps forward and backward in constant time
- Keep 2 pointers
curr
andmax
curr
is used to track the current page being viewedmax
is used to track the limit that we can go forward for- For instance, when we
visit
a url, we incrementcurr
and we need to setmax
to the new value ofcurr
. That’s because the previous forward history is lost when we visit aurl
. - For
back
andforward
, we don’t need to updatemax
, we use0
andmax
as limits forback
andforward
respectively.
With all these ideas, the implementation becomes quite clear:
class BrowserHistory {
private String[] history;
private int curr;
private int max;
public BrowserHistory(String homepage) {
history = new String[5001];
history[0] = homepage…