Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1441. Build an Array With Stack Operations

ArrayStackSimulation

Explanation

To solve this problem, we can simulate the stack operations based on the given rules. We iterate through the numbers from 1 to n and check if the current number is in the target array. If it is, we push it onto the stack. If it's not, we push the number onto the stack and immediately pop it to simulate not using it. We continue this process until the stack matches the target array or we reach the end of the numbers from 1 to n.

Algorithm:

  1. Initialize an empty stack to store the elements.
  2. Iterate through the numbers from 1 to n:
    • If the current number is in the target array, push it onto the stack.
    • If the current number is not in the target array, push it onto the stack and immediately pop it.
    • Check if the stack matches the target array. If it does, stop the iterations.
  3. Return the stack operations as the output.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the value of the input parameter n.

Space Complexity:

The space complexity of this algorithm is O(n) since the stack can potentially store all n elements.

class Solution {
    public List<String> buildArray(int[] target, int n) {
        List<String> result = new ArrayList<>();
        Stack<Integer> stack = new Stack<>();
        
        int index = 0;
        for (int i = 1; i <= n && index < target.length; i++) {
            stack.push(i);
            result.add("Push");
            
            if (stack.peek() != target[index]) {
                stack.pop();
                result.add("Pop");
            } else {
                index++;
            }
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.