Build an Array With Stack Operations

medium stack simulation array

Problem

You are given a strictly increasing list of integers target whose values come from the stream 1, 2, 3, …, n. Using only the operations "Push" (read the next number from the stream onto a stack) and "Pop" (remove the top of the stack), produce a sequence of operations so that the stack ends up exactly equal to target. Stop reading once every number in target has been placed, and return the list of operations used.

Inputtarget = [1, 3], n = 3
Output["Push", "Push", "Pop", "Push"]
Read 1 → Push (keep). Read 2 → Push then Pop (2 is not in target). Read 3 → Push (keep). Stack is now [1, 3].

def build_array(target, n):
    ops = []
    cur = 1
    for want in target:
        while cur < want:
            ops.append("Push")
            ops.append("Pop")
            cur += 1
        ops.append("Push")
        cur += 1
    return ops
function buildArray(target, n) {
  const ops = [];
  let cur = 1;
  for (const want of target) {
    while (cur < want) {
      ops.push("Push");
      ops.push("Pop");
      cur += 1;
    }
    ops.push("Push");
    cur += 1;
  }
  return ops;
}
class Solution {
    public List<String> buildArray(int[] target, int n) {
        List<String> ops = new ArrayList<>();
        int cur = 1;
        for (int want : target) {
            while (cur < want) {
                ops.add("Push");
                ops.add("Pop");
                cur += 1;
            }
            ops.add("Push");
            cur += 1;
        }
        return ops;
    }
}
vector<string> buildArray(vector<int>& target, int n) {
    vector<string> ops;
    int cur = 1;
    for (int want : target) {
        while (cur < want) {
            ops.push_back("Push");
            ops.push_back("Pop");
            cur += 1;
        }
        ops.push_back("Push");
        cur += 1;
    }
    return ops;
}
Time: O(n) Space: O(n)