Ctrl K

Taking Cards From the End

Easy
Numbered cards lie in a row, given as the array stack. In one move you may take only the last card of the row. You want to end up holding every number from 1 to need (each at least once). What is the smallest number of moves that achieves this? Cards you do not need still have to be taken if they are in the way; they simply do not count.
Example 1
stack=[4, 2, 3, 1, 4], need=2 → 4

Taking from the end we get 4, 1, 3, 2. After the fourth move we hold both 1 and 2.

Example 2
stack=[1, 3, 2], need=3 → 3

To have 1, 2 and 3 you have to take all three cards.

Example 3
stack=[2, 2, 1], need=1 → 1
Constraints
  • 1 ≤ len(stack) ≤ 50
  • 1 ≤ stack[i] ≤ len(stack)
  • 1 ≤ need ≤ len(stack)
  • Every number from 1 to need appears in stack
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Lost Ticket EasyDoubled Tag, Lost Tag EasyWords From Working Keys EasyIn at Least Two Lists EasyMatching Sock Pairs Easy
loading Python…
Input
stack=[4, 2, 3, 1, 4], need=2
Expected
4

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