Build an Array With Stack Operations

You are given an integer array `target` and an integer `n`. You have an empty stack and a stream of the integers `1, 2, ..., n`. Two operations are allowed: - **"Push"**: read the next integer from the stream and push it onto the stack. - **"Pop"**: remove the integer on the top of the stack. Build the stack so that, from bottom to top, it equals `target`. Stop reading the stream once it does. Return the operations used. The answer is unique.

30:00

Build an Array With Stack Operations
medium
Free written solution
Topics
Companies

You are given an integer array target and an integer n. You have an empty stack and a stream of the integers 1, 2, ..., n.

Two operations are allowed:

  • "Push": read the next integer from the stream and push it onto the stack.
  • "Pop": remove the integer on the top of the stack.

Build the stack so that, from bottom to top, it equals target. Stop reading the stream once it does. Return the operations used. The answer is unique.

Example 1:
Input: {"target":[1,3],"n":3}
Output: ["Push","Push","Pop","Push"]
Constraints:
  • 1≤target.length≤1001 \leq \text{target.length} \leq 100

  • 1≤n≤1001 \leq n \leq 100

  • 1≤target[i]≤n1 \leq \text{target}[i] \leq n

  • target is strictly increasing.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"target":[1,3],"n":3}

The stream will hand out 1, 2, ..., 3 in order. The stack must end up as [1, 3] from bottom to top.

stream 1..3 (next = 1)

1
2
3

blue = wanted by target, red = pushed then popped, green = kept

stack (top first)

empty

popped (0)

nothing yet

target (0/2 built)

1
3

ops (0)

Variables
VariableValue
cur1
ops0
DepthFunction Call
Stack empty
0/6