[LeetCode]#1441. Build an Array With Stack 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.
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]
  1. Check 1 in target and answer is yes. Add “Push” in list.
  2. Check 2 in target and answer is No. Add “Push” and “Pop” in list.
  3. Check 3 in target and answer is yes. Add “Push” in list.
  4. Return [‘Push’, ‘Push’, ‘Pop’, ‘Push’]
class Solution:
def buildArray(self, target, n):
ans = []
move = 0
for i in range(1, n+1):
ans.append("Push")
move += 1
if i not in target:
ans.append("Pop")
move -= 1
if move == len(target):
break
return ans

Interesting in any computer science.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Connected cars 🏎 — what are they and how to get started developing connected car apps

Managed IT Services in Fulney #Managed #IT #Services #Fulney https://t.co/3Qm0MEWzPj

PYTHON FOR GAMING ? IS IT FLEXIBLE? IF NOT, WHAT ARE THE ALTERNATIVES LANGUAGES?

SecurityTube Linux Assembly Expert (SLAE) Assignment Writeups — \x06 Writing Polymorphic Shellcode

PancakeSwap Listing and Turbulence

Day 9 — Another brick in the wall

PhpStorm for Mac slow on 4K? Nope!

Today was another wonderful day in AMAZON WEB SERVICES.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Fatboy Slim

Fatboy Slim

Interesting in any computer science.

More from Medium

How to implement a Queue class using deque. PYTHON data structures and algorithm.

Automatically generating SQLAlchemy models — #22

How to deploy FastAPI on IIS server

[Study][Python] lambda