Skip to content

1441. Build an Array With Stack Operations Medium

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 bottom to 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 bottom to 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.

Example 1:
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation:
Read 1 and push it to the stack. -> [1]
Read 2 and push it to the stack, then pop it. -> [1]
Read 3 and push it to the stack. -> [1,3]

Example 2:
Input: target = [1,2,3], n = 3
Output: ["Push","Push","Push"]

Example 3:
Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: Only the first 2 integers are required.

Approach

Input: A target array target (strictly increasing) and an integer n

Output: Return the operation sequence (consisting of "Push" and "Pop") required to construct the target array

This problem belongs to the Basic Stack Simulation category.

  1. Initialize variables: curr = 1, res = [], representing the currently read number and the operation sequence, respectively.
  2. Iterate through each number num in target:
    • If curr < num: This means the current number is not the target value, so we execute "Push" + "Pop" to discard it, and increment curr.
    • If curr == num: We execute "Push" to retain it, and increment curr.
  3. Finally, return the operation sequence res.

Implementation

python
class Solution:
    def buildArray(self, target: List[int], n: int) -> List[str]:
        curr = 1           # Currently read number, increasing from 1
        res = []           # Used to record the operation sequence ('Push' and 'Pop')

        # Iterate over every target number in target
        for num in target:
            # If the current number is smaller than the target, this number is not what we want
            # We need to perform Push then Pop, reading it and deleting it immediately
            while curr < num:
                res.append('Push')   # Read this number
                res.append('Pop')    # Delete it immediately (since it's not in target)
                curr += 1            # Prepare to read the next number
            
            # The current number equals the target number, keep it directly (Push)
            res.append('Push')
            curr += 1                # Move to the next number
        
        return res                   # Return the complete operation sequence
javascript
/**
 * @param {number[]} target
 * @param {number} n
 * @return {string[]}
 */
const buildArray = function(target, n) {
    let curr = 1;
    const ans = [];

    for (let num of target) {
        while (curr < num) {
            ans.push('Push');
            ans.push('Pop');
            curr ++;
        }

        ans.push('Push');
        curr ++;
    }

    return ans;
};

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1441. Build an Array With Stack Operations (English)

1441. 用栈操作构建数组 (Chinese)