Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1441: Build an Array With Stack Operations

In this guide, we solve Leetcode #1441 Build an Array With Stack Operations in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Stack, Array, Simulation

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

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].

Python Solution

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

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of the array target\textit{target}target. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy