Skip to content
the poor coder

Leetcode - Build an Array With Stack Operations Solution

Poor Man
Published
Updated
Reading time
2 min read

Given an array target and an integer n. In each iteration, you will read a number from  list = {1,2,3..., n}.

Build the target array using the following operations:

  • Push: Read a new element from the beginning list, and push it in the array.
  • Pop: delete the last element of the array.
  • If the target array is already built, stop reading more elements.

Return the operations to build the target array. You are guaranteed that the answer is unique.

Example 1:

Text
Input: target = [1,3], n = 3
Output: ["Push","Push","Pop","Push"]
Explanation: 
Read number 1 and automatically push in the array -> [1]
Read number 2 and automatically push in the array then Pop it -> [1]
Read number 3 and automatically push in the array -> [1,3]

Example 2:

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

Example 3:

Text
Input: target = [1,2], n = 4
Output: ["Push","Push"]
Explanation: You only need to read the first 2 numbers and stop.

Example 4:

Text
Input: target = [2,3,4], n = 4
Output: ["Push","Pop","Push","Push","Push"]

Constraints:

  • 1 <= target.length <= 100
  • 1 <= target[i] <= n
  • 1 <= n <= 100
  • target is strictly increasing.

Solution in Python#

Python
class Solution:
    def buildArray(self, target: List[int], n: int) -> List[str]:
        stack = []
        target = [0]+target
        for i in range(1,len(target)):
            diff = target[i]-target[i-1]-1
            stack.extend(["Push", "Pop"]*diff)
            stack.append("Push")
        return stack

Keep going

2021

Leetcode - Crawler Log Folder Solution

The Leetcode file system keeps a log each time some user performs a change folder operation. The operations are described below: "../" : Move to the parent folder of the current folder. (If you are already in the main…

leetcodestack1 min read
2021

Leetcode - Make The String Great Solution

Given a string s of lower and upper case English letters. A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where: 0 <= i <= s.length - 2 s[i] is a lower-case letter and s[i + 1] is…

ESC