Build an Array With Stack Operations (LeetCode 1441): Solution and Explanation
A stream hands out 1, 2, ..., n in order and you can only Push the next number or Pop the top of the stack. Produce the operations that leave exactly target on the stack, stopping as soon as it is built.
Intuition
The stream never goes backwards and every number you read has to be pushed. So for each number the only choice is whether it stays on the stack or is popped right away.
Because target is strictly increasing, the numbers you want arrive in the same order they must sit on the stack. A number in target is pushed and kept; a number between two target values is pushed and immediately popped.
Once the last target value is on the stack you are done. Reading any further number would force a Push and a Pop for nothing, and the problem asks you to stop.
Approach: Simulate the stream with one counter
- Start with an empty list
opsandcur = 1, the next number in the stream. - For each value
tintarget: whilecur < t, append "Push" and "Pop" and incrementcur. - Append "Push" for
titself and incrementcur. - Return
opsafter the last target value.
Step-by-step example
target = [1,3], n = 3
- cur = 1 and the first target is 1: Push 1 and keep it. ops = [Push].
- Next target is 3, but the stream gives 2 first: Push 2, then Pop it. ops = [Push, Push, Pop].
- The stream gives 3, which is wanted: Push it. ops = [Push, Push, Pop, Push].
- The stack holds [1,3], equal to target, so stop.
Code: Python, Java, C++
1class Solution:
2 def buildArray(self, target: List[int], n: int) -> List[str]:
3 ops = []
4 cur = 1
5 for t in target:
6 while cur < t:
7 ops.append("Push")
8 ops.append("Pop")
9 cur += 1
10 ops.append("Push")
11 cur += 1
12 return ops1class Solution {
2 public List<String> buildArray(int[] target, int n) {
3 List<String> ops = new ArrayList<>();
4 int cur = 1;
5 for (int t : target) {
6 while (cur < t) {
7 ops.add("Push");
8 ops.add("Pop");
9 cur++;
10 }
11 ops.add("Push");
12 cur++;
13 }
14 return ops;
15 }
16}1class Solution {
2public:
3 vector<string> buildArray(vector<int>& target, int n) {
4 vector<string> ops;
5 int cur = 1;
6 for (int t : target) {
7 while (cur < t) {
8 ops.push_back("Push");
9 ops.push_back("Pop");
10 cur++;
11 }
12 ops.push_back("Push");
13 cur++;
14 }
15 return ops;
16 }
17};Time and space complexity
O(m)
m is the last value of target. Each number up to m produces one or two operations.
O(1)
Only the counter besides the returned list of operations (which is at most 2m long).
Other approaches
Walk the stream with a target pointer (time O(m), space O(1))
Loop v from 1 to the last target value, keep an index into target, and emit Push for each v, plus Pop when v is not the current target. Same output, the loop just runs over the stream instead of over target.
Simulate a real stack (time O(m), space O(m))
Actually push and pop values on a stack and compare it with target after each step. It works, but the stack never needs to be inspected, so it only adds overhead.
Common mistakes
- Looping all the way to
n. Numbers after the last target value must not be read, otherwise extra Push and Pop pairs appear. - Forgetting that a skipped number still needs a Push before its Pop; you cannot skip the stream without reading it.
- Checking membership in target with a linear search inside the loop, which turns an easy O(m) solution into O(m * k).
- Treating
nas the stopping point in tests like target = [1,2], n = 4, where the correct answer has only two operations.
Frequently asked questions
Why is the answer unique?
Every number read must be pushed, and a pushed number not in target has to be popped before the next wanted number arrives. Stopping right after the last target removes the only other freedom, so there is exactly one sequence.
What is n used for?
It only bounds the stream. Since every target value is at most n, the loop never runs past it, so n does not appear in the logic.
What is the time and space complexity?
O(m) time where m is the last target value, and O(1) extra space apart from the returned list.