Ctrl K

A Stack From a Number Stream

Medium
The numbers 1, 2, ..., limit arrive one at a time in increasing order. You have an empty stack and two operations: - "Push": take the next number from the stream and put it on top of the stack; - "Pop": remove the number on top of the stack. The stack, read from bottom to top, must end up equal to the strictly increasing array wanted. As soon as that happens, you stop: no more operations and no more numbers read from the stream. Return the sequence of operations that produces wanted.
Example 1
wanted=[2, 3], limit=4 → ['Push', 'Pop', 'Push', 'Push']

Take 1 and remove it right away, then push 2 and 3. The stack is now [2, 3], so we stop and never read 4.

Example 2
wanted=[1, 4], limit=4 → ['Push', 'Push', 'Pop', 'Push', 'Pop', 'Push']

1 stays, 2 and 3 are pushed and popped at once, then 4 is pushed.

Example 3
wanted=[1, 2, 3], limit=3 → ['Push', 'Push', 'Push']
Constraints
  • 1 ≤ limit ≤ 100
  • 1 ≤ len(wanted) ≤ 100
  • 1 ≤ wanted[i] ≤ limit
  • wanted is strictly increasing
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsRobots Clashing on a Rail MediumReplaying Stack Pushes and Pops MediumQuiz Score Log EasyA Picky Line at the Counter EasyRobots Crashing on a Rail Hard
loading Python…
Input
wanted=[2, 3], limit=4
Expected
['Push', 'Pop', 'Push', 'Push']

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