AlgoMaster Logo

Design Browser History

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Using a List to Store History

Intuition:

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.

Execution:

  • Use an ArrayList to store the web pages.
  • Maintain an integer current to track the index of the current web page.
  • On visiting a new page, all forward history (if any) is removed, and the new URL is appended.

Details:

  1. visit(String url): Add the url to the history at the current position and remove any forward history. Update the current position.
  2. back(int steps): Move the current position back by steps or until reaching the first page.
  3. forward(int steps): Move the current position forward by steps or until reaching the last page.

Code:

2. Using Two Stacks

Intuition:

To optimize the operations for forward and backward navigation, two stacks can be used:

  • One stack to hold the history we can go back to.
  • Another stack to hold the history we can move forward to.

Execution:

  • Use a current variable to track the active page.
  • On visit, clear the forward stack and push the current page to the backward stack before visiting the new page.
  • For back, push the current page to the forward stack and pop from the backward stack.
  • For forward, pop from the forward stack and push to the backward stack.

Details:

  1. visit(String url): Push current page to the back stack, clear forward stack, and set visited page as current.
  2. back(int steps): Move as many steps back from the back stack, adjusting the current page.
  3. forward(int steps): Move as many steps forward from the forward stack, adjusting the current page.

Code: