1441. Build an Array With Stack Operations

Difficulty:
Related Topics:
Similar Questions:

    Problem

    You are given an integer array target and an integer n.

    You have an empty stack with the two following operations:

    You also have a stream of the integers in the range [1, n].

    Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to target. You should follow the following rules:

    Return **the stack operations needed to build **target following the mentioned rules. If there are multiple valid answers, return any of them.

      Example 1:

    Input: target = [1,3], n = 3
    Output: ["Push","Push","Pop","Push"]
    Explanation: Initially the stack s is empty. The last element is the top of the stack.
    Read 1 from the stream and push it to the stack. s = [1].
    Read 2 from the stream and push it to the stack. s = [1,2].
    Pop the integer on the top of the stack. s = [1].
    Read 3 from the stream and push it to the stack. s = [1,3].
    

    Example 2:

    Input: target = [1,2,3], n = 3
    Output: ["Push","Push","Push"]
    Explanation: Initially the stack s is empty. The last element is the top of the stack.
    Read 1 from the stream and push it to the stack. s = [1].
    Read 2 from the stream and push it to the stack. s = [1,2].
    Read 3 from the stream and push it to the stack. s = [1,2,3].
    

    Example 3:

    Input: target = [1,2], n = 4
    Output: ["Push","Push"]
    Explanation: Initially the stack s is empty. The last element is the top of the stack.
    Read 1 from the stream and push it to the stack. s = [1].
    Read 2 from the stream and push it to the stack. s = [1,2].
    Since the stack (from the bottom to the top) is equal to target, we stop the stack operations.
    The answers that read integer 3 from the stream are not accepted.
    

      Constraints:

    Solution (Java)

    class Solution {
        public List<String> buildArray(int[] target, int n) {
            List<String> result = new ArrayList<>();
            Set<Integer> set = new HashSet<>();
            for (int i : target) {
                set.add(i);
            }
            int max = target[target.length - 1];
            for (int i = 1; i <= n; i++) {
                if (!set.contains(i)) {
                    result.add("Push");
                    result.add("Pop");
                } else {
                    result.add("Push");
                }
                if (i == max) {
                    break;
                }
            }
            return result;
        }
    }
    

    Explain:

    nope.

    Complexity: