Ctrl K

Card Pull Positions

Medium
A card index holds a stack of cards cards numbered 1 to cards. At first they are in order, [1, 2, ..., cards], with card 1 on top. A librarian handles the requests in requests one by one. For a request v they find card v, note its position in the stack (the top card is position 0), pull it out and put it back on top. The other cards keep their relative order. Return the noted positions, one per request, in the order the requests were handled.
Example 1
requests=[2, 2, 4, 1], cards=4 → [1, 0, 3, 2]

The stack is [1, 2, 3, 4]. Card 2 sits at position 1, leaving [2, 1, 3, 4]; now 2 is on top, so position 0. Card 4 is at position 3, giving [4, 2, 1, 3], and finally card 1 is at position 2.

Example 2
requests=[3], cards=3 → [2]

A single request: card 3 is at the very bottom of [1, 2, 3], position 2.

Example 3
requests=[1, 1, 1], cards=2 → [0, 0, 0]

Card 1 starts on top and goes back on top after every request, so every answer is 0.

Constraints
  • 1 ≤ cards ≤ 1000
  • 1 ≤ requests.length ≤ 1000
  • 1 ≤ requests[i] ≤ cards
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo Piles by Larger Count HardSpiral Readout MediumSpiral-Numbered Square MediumNext Step of a Cell Colony MediumRebuild the Line from Height Records Medium
loading Python…
Input
requests=[2, 2, 4, 1], cards=4
Expected
[1, 0, 3, 2]

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