Social feed~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1472linked-lists
A social app opens links in its own browser. The browser keeps a history of the pages you visited, with the current page somewhere in it. Back and Forward buttons move along the history, and the user can jump several pages at once.
Visiting a new page while you are in the middle of the history drops every page ahead of you, as a normal browser does. The history is a doubly linked list: each page knows the page before it and the page after it.
Write run_history(first, commands, args).
first, with no other history.commands[i] is "visit", "back" or "forward", and args[i] is a list with one number, x."visit": go to page x. It becomes the current page, and every page ahead of the old current page is dropped."back": go back x pages, or as many as the history allows. "forward": go forward x pages, or as many as the history allows."back" and each "forward", record the id of the current page. Return those ids in order. A "visit" records nothing.For the tests, x is at most 100 for "back" and "forward".
Input: first = 3, commands = ["visit", "visit", "back", "visit", "forward", "back", "forward"], args = [[8], [2], [1], [9], [1], [5], [1]]
Output: [8, 9, 3, 8]| Step | Command | History (current in brackets) | Answer |
|---|---|---|---|
| [1] | start | [3] | |
| [2] | visit 8 | 3 → [8] | |
| [2] | visit 2 | 3 → 8 → [2] | |
| [3] | back 1 | 3 → [8] → 2 | 8 |
| [2] | visit 9 | 3 → 8 → [9] | |
| [4] | forward 1 | 3 → 8 → [9] | 9 |
| [3] | back 5 | [3] → 8 → 9 | 3 |
| [4] | forward 1 | 3 → [8] → 9 | 8 |
Input: first = 7, commands = ["back"], args = [[3]]
Output: [7]There is nothing behind the first page, so the browser stays on it.
Input: first = 1, commands = ["visit", "forward"], args = [[2], [4]]
Output: [2]There is nothing ahead of the newest page, so forward stays on it.
1 ≤ commands.length = args.length ≤ 100,000args[i] has exactly one number from 1 to 1,000,000. For "back" and "forward" it is at most 100.Rebuilding the whole history list on every visit copies up to n entries each time. With 10^5 visits, that is about 5 × 10^9 entry copies.
A visit that only adds one node and re-points one pointer costs a constant number of steps.