#1441
Medium Algorithms Build an array with stack operations
Array Stack Simulation
81.0% acceptance
Feb 25, 2026
1216
533
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.
Return the stack operations needed to build target following the mentioned rules. If there are multiple valid answers, return any of them.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn build_array(target: Vec<i32>, _n: i32) -> Vec<String> {
let mut result = vec![];
let mut ti = 0;
let mut cur = 1i32;
while ti < target.len() {
result.push("Push".to_string());
if cur == target[ti] {
ti += 1;
} else {
result.push("Pop".to_string());
}
cur += 1;
}
result
}
}