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.
You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive.
Return the operations to build the target array.
You are guaranteed that the answer is unique.
Example 1:
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]
Analysis:
Check 1 in target and answer is yes. Add “Push” in list.
Check 2 in target and answer is No. Add “Push” and “Pop” in list.
Check 3 in target and answer is yes. Add “Push” in list.
Return [‘Push’, ‘Push’, ‘Pop’, ‘Push’]
Press enter or click to view image in full size
Solution:
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