[LeetCode] Build an Array With Stack Operations

1441. Build an Array With Stack Operations

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<string> buildArray(vector<int>& target, int n) {
vector<string> res;
const string PUSH = "Push";
const string POP = "Pop";
for(int i = 0, now = 1; i < target.size(); i++) {
while(now != target[i]) {
res.push_back(PUSH);
res.push_back(POP);
now++;
}
res.push_back(PUSH);
now++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/22/PS/LeetCode/build-an-array-with-stack-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.