Problem Description
Given an integer array target and an integer n, simulate operations on an initially empty stack using only "Push" and "Pop" operations. You process numbers from 1 to n sequentially. For each number, if it is in target, you perform a "Push" (adding it to the stack) otherwise you perform a "Push" followed immediately by a "Pop" (to ignore it). Once the stack contains the target sequence (from bottom to top), the operations stop. Return the list of operations used to build the target array.
Key Insights
- Since target is strictly increasing, the stream must be processed sequentially until target’s last element is reached.
- For each integer from 1 to target[-1], decide whether to simply push (if it matches the next target value) or push then pop (if it does not).
- The operations stop as soon as the target is fully constructed, so numbers beyond the last element in target are not processed.
Space and Time Complexity
Time Complexity: O(k) where k is the value of target[-1] (in worst-case, it iterates through numbers 1 to target[-1]). Space Complexity: O(m) where m is the number of operations stored (which in worst-case is roughly 2*m where m is the length of target)
Solution
The solution uses a simple iteration over the range [1, target[-1]]. A pointer is used to track the current index in the target array. For each number:
- If the current number equals the target at the pointer position, perform a "Push" and increment the pointer.
- If it does not match, perform a "Push" followed by a "Pop" to discard the number. This simulation mimics stack operations with a simple control flow. The algorithm stops once all elements in target have been processed. The main data structure used is a list for storing the operations.