Member-only story

Leetcode 1472: Design Browser

Pierre-Marie Poitevin
2 min readJun 12, 2020

--

In this Leetcode problem, we try to design a simple code browser with 3 methods: visit, back, forward.

Problem statement

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

  1. We are going to use a simple array String[] as history
  2. 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
  3. Keep 2 pointers curr and max
  4. curr is used to track the current page being viewed
  5. max is used to track the limit that we can go forward for
  6. For instance, when wevisit a url, we increment curr and we need to set max to the new value of curr. That’s because the previous forward history is lost when we visit a url.
  7. For back and forward, we don’t need to update max, we use 0 and max as limits for back and forward 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…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

No responses yet