Build an Array With Stack Operations - Problem
You are given an integer array target and an integer n.
You have an empty stack with the two following operations:
- "Push": pushes an integer to the top of the stack.
- "Pop": removes the integer on the top of the stack.
You also have a stream of the integers in the range [1, n].
Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:
- If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.
- If the stack is not empty, pop the integer at the top of the stack.
- If, at any moment, the elements in the stack (from the bottom to the top) are equal to
target, do not read new integers from the stream and do not do more operations on the stack.
Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.
Input & Output
Example 1 — Basic Case
$
Input:
target = [1,3], n = 5
›
Output:
["Push","Push","Pop","Push"]
💡 Note:
Stream is [1,2,3,4,5]. Push 1 (matches target[0]), Push 2 (doesn't match target[1]), Pop 2, Push 3 (matches target[1]). Target complete.
Example 2 — Consecutive Numbers
$
Input:
target = [1,2,3], n = 3
›
Output:
["Push","Push","Push"]
💡 Note:
Target contains consecutive numbers 1,2,3 from start of stream. Just push each number without any pops needed.
Example 3 — Single Element
$
Input:
target = [1], n = 1
›
Output:
["Push"]
💡 Note:
Target has only one element which is 1. Stream starts with 1, so just push it once and we're done.
Constraints
- 1 ≤ target.length ≤ 100
- 1 ≤ target[i] ≤ n ≤ 100
- 1 ≤ n ≤ 100
- target is strictly increasing
Visualization
Tap to expand
Understanding the Visualization
1
Input
Stream [1,2,3,4,5] and target [1,3]
2
Process
Use Push/Pop operations to build target
3
Output
Sequence of operations: ["Push","Push","Pop","Push"]
Key Takeaway
🎯 Key Insight: Process stream sequentially, push every number but immediately pop those not needed in target
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code