Ctrl K

The Back Button

Easy
A user browses numbered pages. Their actions are recorded in the array actions: a positive number means they opened the page with that number, and -1 means they pressed the Back button. The button works like this: if it is the k-th Back press in a row (with no pages opened in between), it shows the k-th page from the end of the history: the most recently opened one for k = 1, the one before it for k = 2, and so on. If the history holds fewer than k pages, the button shows -1. Opening a new page resets the press counter; pressing Back never changes the history itself. Return the list of what the button showed, in the order of the presses.
Example 1
actions=[5, 8, 3, -1, -1, -1, -1] → [3, 8, 5, -1]

The history is 3 (latest), 8, 5. Four back presses in a row give 3, 8, 5, and on the fourth the history runs out, so -1.

Example 2
actions=[-1, 7, -1, 2, -1, -1] → [-1, 7, 2, 7]

The first press finds an empty history: -1. After 7, a press gives 7. After 2 the streak restarts: 2, then 7.

Example 3
actions=[4, 4, -1, -1] → [4, 4]
Constraints
  • 1 ≤ len(actions) ≤ 100
  • actions[i] = -1 or 1 ≤ actions[i] ≤ 100
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHow Long the Light Stayed On EasyRepack the Tray EasyQuiz Score Log EasyMirror and Negate a Bitmap EasySwap Rows and Columns Easy
loading Python…
Input
actions=[5, 8, 3, -1, -1, -1, -1]
Expected
[3, 8, 5, -1]

Run checks the first 3 tests in your browser. Submit checks all 263 tests on the server, hidden ones included.