#1441

Build an Array With Stack Operations

Medium
ArrayStackSimulationStackSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach directly constructs the operations needed by recognizing that we only need to push the numbers in the target array and pop the numbers in between them. This avoids unnecessary operations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty list for operations.
  2. 2Step 2: Iterate through each number in the target array.
  3. 3Step 3: For each number, push it onto the stack and record the operation.
  4. 4Step 4: If the current number is not the last in the target, add a 'Pop' operation to discard the next number.
solution.py7 lines
1def buildArray(target, n):
2    operations = []
3    for i in range(1, target[-1] + 1):
4        operations.append('Push')
5        if i != target[len(operations) - 1]:
6            operations.append('Pop')
7    return operations

Complexity note: This complexity is optimal because we only iterate through the target array and perform a constant amount of work for each element.

  • 1Recognizing unnecessary operations can lead to a more efficient solution.
  • 2Understanding stack behavior is crucial for simulating operations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.