Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
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.
Example 1:
Input: target = [1,3], n = 3 Output: ["Push","Push","Pop","Push"] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1,2]. Pop the integer on the top of the stack. s = [1]. Read 3 from the stream and push it to the stack. s = [1,3].
Example 2:
Input: target = [1,2,3], n = 3 Output: ["Push","Push","Push"] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1,2]. Read 3 from the stream and push it to the stack. s = [1,2,3].
Example 3:
Input: target = [1,2], n = 4 Output: ["Push","Push"] Explanation: Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = [1]. Read 2 from the stream and push it to the stack. s = [1,2]. Since the stack (from the bottom to the top) is equal to target, we stop the stack operations. The answers that read integer 3 from the stream are not accepted.
Constraints:
1 <= target.length <= 1001 <= n <= 1001 <= target[i] <= ntarget is strictly increasing.Problem summary: 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
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Stack
[1,3] 3
[1,2,3] 3
[1,2] 4
minimum-operations-to-collect-elements)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1441: Build an Array With Stack Operations
class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> ans = new ArrayList<>();
int cur = 1;
for (int x : target) {
while (cur < x) {
ans.addAll(List.of("Push", "Pop"));
++cur;
}
ans.add("Push");
++cur;
}
return ans;
}
}
// Accepted solution for LeetCode #1441: Build an Array With Stack Operations
func buildArray(target []int, n int) (ans []string) {
cur := 1
for _, x := range target {
for ; cur < x; cur++ {
ans = append(ans, "Push", "Pop")
}
ans = append(ans, "Push")
cur++
}
return
}
# Accepted solution for LeetCode #1441: Build an Array With Stack Operations
class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
ans = []
cur = 1
for x in target:
while cur < x:
ans.extend(["Push", "Pop"])
cur += 1
ans.append("Push")
cur += 1
return ans
// Accepted solution for LeetCode #1441: Build an Array With Stack Operations
impl Solution {
pub fn build_array(target: Vec<i32>, n: i32) -> Vec<String> {
let mut ans = Vec::new();
let mut cur = 1;
for &x in &target {
while cur < x {
ans.push("Push".to_string());
ans.push("Pop".to_string());
cur += 1;
}
ans.push("Push".to_string());
cur += 1;
}
ans
}
}
// Accepted solution for LeetCode #1441: Build an Array With Stack Operations
function buildArray(target: number[], n: number): string[] {
const ans: string[] = [];
let cur: number = 1;
for (const x of target) {
for (; cur < x; ++cur) {
ans.push('Push', 'Pop');
}
ans.push('Push');
++cur;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.