Bird
Raised Fist0
Interview Prepstacks-monotonic-stackeasyAmazonBloombergGoogle

Implement Queue Using Stacks

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize the Queue

Create an empty queue with two empty stacks: push_stack and pop_stack.

💡 Starting with empty stacks sets the foundation for all future operations.
Line:def __init__(self): self.push_stack = [] self.pop_stack = []
💡 The queue is represented internally by two stacks, both initially empty.
📊
Implement Queue Using Stacks - Watch the Algorithm Execute, Step by Step
Watching each stack operation and transfer step reveals how the queue order is preserved using stacks, which is not obvious from code alone.
Step 1/10
·Active fill★Answer cell
no_op
Stack (top→bottom)
empty
pushElement[0]: 1
Stack (top→bottom)
1
↑ pushed: 1
pushElement[1]: 2
Stack (top→bottom)
2
1
↑ pushed: 2
pop
Stack (top→bottom)
1
↓ popped: [2]
push
Stack (top→bottom)
2
↑ pushed: 2
pop
Stack (top→bottom)
1
2
↓ popped: [1]
peekElement[2]: 1
Stack (top→bottom)
1
2
Contributes: 1
popElement[3]: 1
Stack (top→bottom)
2
↓ popped: [1]
Contributes: 1
no_op
Stack (top→bottom)
2
Contributes: false
no_op
Stack (top→bottom)
2

Key Takeaways

✓ Two stacks can simulate a queue by using one stack for pushing and another for popping, with a transfer step reversing order.

This reversal step is not obvious from code but is critical to preserving queue order.

✓ The transfer from push_stack to pop_stack happens only when pop_stack is empty, making pop and peek operations amortized O(1).

Seeing the transfer visually clarifies why the costly operation is infrequent.

✓ Empty check requires both stacks to be empty, reflecting the queue's true emptiness state.

This condition is subtle and easy to miss without seeing both stacks' states.

Practice

(1/5)
1. Consider the following Python code implementing the Remove K Digits algorithm. What is the final returned value when calling removeKdigits("10200", 1)?
easy
A. "0"
B. "100"
C. "200"
D. "2000"

Solution

  1. Step 1: Trace builder and k during iteration

    Digits: '1', '0', '2', '0', '0' - '1': builder = ['1'], k=1 - '0': '1' > '0', pop '1', k=0, builder = [] - Append '0': builder = ['0'] - '2': builder = ['0', '2'] - '0': '2' > '0', but k=0, no pop - Append '0': builder = ['0', '2', '0'] - '0': builder = ['0', '2', '0', '0']
  2. Step 2: Remove leading zeros and finalize

    k=0, so no slice. Join builder: '0200'. Strip leading zeros: '200'. Return '200'.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Output matches expected minimal number after removing one digit [OK]
Hint: Pop digits while next digit is smaller and k>0 [OK]
Common Mistakes:
  • Forgetting to strip leading zeros
  • Removing wrong digits due to off-by-one in loop
2. Consider the following buggy code for asteroid collision. Which line contains the subtle bug that causes incorrect behavior on equal size asteroids?
def asteroidCollision(asteroids):
    stack = []
    for a in asteroids:
        alive = True
        while alive and stack and stack[-1] > 0 and a < 0:
            if stack[-1] < -a:
                stack.pop()
            elif stack[-1] == -a:
                alive = False
            else:
                alive = False
        if alive:
            stack.append(a)
    return stack
medium
A. Line with 'stack.pop()' inside 'if stack[-1] < -a:'
B. Line with 'while alive and stack and stack[-1] > 0 and a < 0:' condition
C. Line with 'alive = False' inside 'elif stack[-1] == -a:'
D. Line with 'stack.append(a)' after the while loop

Solution

  1. Step 1: Identify behavior on equal size asteroids

    When sizes are equal, both asteroids should explode (pop from stack and not append current).
  2. Step 2: Check code for equal size case

    In the buggy code, stack.pop() is missing when sizes are equal, so the top asteroid remains incorrectly.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Missing stack.pop() causes incorrect survival of equal asteroid [OK]
Hint: Equal size asteroids both must be removed [OK]
Common Mistakes:
  • Forgetting to pop stack on equal size
  • Appending asteroid after it exploded
  • Incorrect while loop condition
3. The following code attempts to compute the largest rectangle area in a histogram using a monotonic stack. Identify the line containing the subtle bug that causes incorrect area calculation in some cases.
def largestRectangleArea(heights):
    n = len(heights)
    left = [-1] * n
    right = [n] * n
    stack = []

    for i in range(n):
        while stack and heights[stack[-1]] >= heights[i]:
            stack.pop()
        left[i] = stack[-1] if stack else -1
        stack.append(i)

    stack.clear()

    for i in range(n - 1, -1, -1):
        while stack and heights[stack[-1]] >= heights[i]:
            stack.pop()
        right[i] = stack[-1] if stack else n
        stack.append(i)

    max_area = 0
    for i in range(n):
        width = right[i] - left[i] - 1
        area = heights[i] * width
        max_area = max(max_area, area)
    return max_area
medium
A. Line with 'while stack and heights[stack[-1]] >= heights[i]:' in right boundary computation
B. Line with 'stack.clear()' before computing right boundaries
C. Line with 'width = right[i] - left[i] - 1' in area calculation
D. Line with 'while stack and heights[stack[-1]] > heights[i]:' in left boundary computation

Solution

  1. Step 1: Compare left boundary condition with right boundary

    Left boundary uses '>=' but right boundary also uses '>='; originally left boundary used '>' causing inconsistency.
  2. Step 2: Identify impact of using '>' instead of '>='

    Using '>' misses popping bars equal in height, leading to wrong left boundaries and smaller area.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Changing '>' to '>=' in left boundary fixes the bug [OK]
Hint: Use consistent '>=' in both boundary computations [OK]
Common Mistakes:
  • Mixing '>' and '>=' causing inconsistent boundaries
  • Forgetting to clear stack before right boundary pass
4. Consider this buggy code for the stock span problem. Which line contains the subtle bug that causes incorrect spans when prices are equal?
medium
A. Line 9: span calculation does not add 1 when stack is not empty
B. Line 11: appending price after appending index to stack
C. Line 6: while condition uses '<' instead of '<='
D. Line 7: popping from stack without checking if empty

Solution

  1. Step 1: Identify the bug in while condition

    The condition uses '<' instead of '<=', so equal prices are not popped, causing incorrect spans.
  2. Step 2: Confirm other lines are correct

    Span calculation correctly handles empty stack. Appending order is correct. Stack emptiness is checked before popping.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Using '<=' ensures equal prices are popped for correct spans [OK]
Hint: Use '<=' in while to pop equal or smaller prices [OK]
Common Mistakes:
  • Using '<' causes incorrect spans for equal prices
  • Misplaced span calculation
5. Suppose the problem is modified so that digits can be removed multiple times (i.e., you can remove the same digit repeatedly if it appears multiple times), or the input string can contain non-digit characters. Which modification to the original algorithm is necessary to handle these changes correctly?
hard
A. Use a frequency map to track digit counts and remove digits greedily based on frequency
B. Switch to a brute force approach generating all subsequences since greedy no longer applies
C. Preprocess input to filter out non-digit characters and apply the same monotonic stack algorithm without changes
D. Modify the stack to allow re-insertion of digits and skip non-digit characters during iteration

Solution

  1. Step 1: Analyze impact of repeated removals and non-digit chars

    Allowing multiple removals of the same digit requires the stack to handle re-insertion or multiple passes. Non-digit chars must be skipped to avoid errors.
  2. Step 2: Identify necessary algorithm modification

    The stack must be adapted to allow re-insertion or multiple removals, and iteration must skip non-digit characters to maintain correctness.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Handling input sanitization and stack flexibility is key for this variant [OK]
Hint: Stack must handle re-insertions and skip invalid chars [OK]
Common Mistakes:
  • Assuming original algorithm works unchanged
  • Ignoring input sanitization
  • Switching to brute force unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard