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 an Array With Stack Operations INPUT target array: 1 3 [0] [1] stream [1, n]: 1 2 3 4 5 Empty Stack: (empty) n = 5 ALGORITHM STEPS 1 Read stream: 1 1 in target: Push "Push" 2 Read stream: 2 2 not in target: Push+Pop "Push","Pop" 3 Read stream: 3 3 in target: Push "Push" 4 Early Termination target built, stop at 3 (skip 4, 5) Final Stack State: 3 1 top FINAL RESULT Operations List: "Push" "Push" "Pop" "Push" Verification: Stack = [1, 3] Target = [1, 3] OK 4 operations total Key Insight: Early Termination Optimization Stop processing the stream once all target elements are built. No need to process numbers after max(target). For target=[1,3], stop at 3 instead of processing 4 and 5. Time: O(max(target)), Space: O(1). TutorialsPoint - Build an Array With Stack Operations | Early Termination Optimization
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