Build an Array With Stack Operations — LeetCode 1441 Python Solution

MediumStackArraySimulation
Problem
#1441
Pattern
Stack
Reading time
2 min

The problem

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.

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.

Python solution

Python
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

MeasureComplexity
TimeO(n), where n is the length of the array \textit{target}
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1441. Build an Array With Stack Operations is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1441. Build an Array With Stack Operations?
LeetCode 1441. Build an Array With Stack Operations is rated Medium on LeetCode.
What is the time complexity of LeetCode 1441. Build an Array With Stack Operations?
The Python solution on this page runs in O(n), where n is the length of the array \textit{target}.
What is the space complexity of LeetCode 1441. Build an Array With Stack Operations?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1441. Build an Array With Stack Operations cover?
LeetCode 1441. Build an Array With Stack Operations is tagged Stack, Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview