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
Build Array With Stack OperationsStream: [1,2,3,4,5]12345Target: [1,3]13Stack Simulation1: Push(1) → Stack: [1] ✓2: Push(2) → Stack: [1,2] → Pop(2) → Stack: [1] ✓3: Push(3) → Stack: [1,3] ✓ Target Complete!Operations: ["Push","Push","Pop","Push"]Time: O(max(target)), Space: O(1)
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
Asked in
Amazon 15 Microsoft 12
23.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen