Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Design Browser History

Stacksmedium

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Design browser history starting on a homepage. Implement `BrowserHistory`: - `new BrowserHistory(homepage)`. - `visit(url)` goes to url from the current page, clearing any forward history. - `back(steps)` moves back up to steps pages and returns the current url. - `forward(steps)` moves forward up to steps pages and returns the current url. - `current()` returns the current url.

Examples

Input: home 'a': visit('b'), visit('c'), back(1), back(1), forward(1), visit('d'), forward(2)
Output: ['b', 'a', 'b', 'd']
Visiting 'd' clears forward history, so the final forward(2) stays on 'd'.

Sample tests

Input: navigate back, forward, and branch
Output: ["b","a","b","d"]
Input: back beyond start clamps
Output: "home"

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Not clearing forward history on a new visit.
  • Letting the index go out of bounds; clamp with min and max.

Learning resources

  • Wikipedia: Stack
Approach & explanation (try first)

An array of visited pages with a current-position index supports back/forward by clamping the index; visiting truncates the forward portion. O(1) per navigation (visit is O(n) due to the truncation).

Loading...
⌘/Ctrl + Enter

Run your code to see results.