Build an Array with Stack Operations

Build an Array with Stack Operations

Leetcode 1441 - Medium Level

ยท

2 min read

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

You have an empty stack with the two following operations:

  • "Push": pushes an integer to the top of the stack.

  • "Pop": removes the integer on the top of the stack.

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:

  • If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack.

  • If the stack is not empty, pop the integer at the top of the stack.

  • If, at any moment, the elements in the stack (from the bottom to the top) are equal to target, do not read new integers from the stream and do not do more operations on the stack.

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

class Solution {
    public List<String> buildArray(int[] target, int n) {
        // Calculate the expected number of elements in the stack
        int nums = target.length + ((target[target.length - 1] - target.length) * 2);

        // Initialize a list to store the stack operations
        List<String> s = new ArrayList<String>(nums);

        // Initialize a variable to keep track of the current value to be pushed onto the stack
        int input = 1;

        // Iterate through the target array
        for (int i : target) {
            // If the current target value is not equal to the current input value
            if (input != i) {
                // Add "Push" and "Pop" operations until they become equal
                while (input != i) {
                    s.add("Push");
                    s.add("Pop");
                    input++;
                }
                // Add a "Push" operation
                s.add("Push");
                input++;
            } else {
                // If the current target value is equal to the current input value, add a "Push" operation
                s.add("Push");
                input++;
            }
        }
        // Return the list of stack operations
        return s;
    }
}

Runtime- 0 ms โœ…

Feel free to explore logic in more detailed way!

ย