#1172

Dinner Plate Stacks

Hard
Hash TableStackDesignHeap (Priority Queue)Hash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n) for push and pop operations, O(1) for popAtStack
Space
O(n)
O(n)
💡

Intuition

Time O(log n) for push and pop operations, O(1) for popAtStackSpace O(n)

In the optimal solution, we maintain a list of stacks along with a min-heap (priority queue) to efficiently track the leftmost available stack for pushing and the rightmost non-empty stack for popping. This allows us to perform operations in a more efficient manner.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a list to hold stacks and a min-heap to track available stacks.
  2. 2Step 2: For push, check the min-heap for the leftmost available stack and push the value. If no stack is available, create a new one.
  3. 3Step 3: For pop, use the last stack in the list to pop the top value. If it becomes empty, remove it from the list.
  4. 4Step 4: For popAtStack, directly access the specified index and pop the top value if it exists.
solution.py33 lines
1import heapq
2
3class DinnerPlates:
4    def __init__(self, capacity: int):
5        self.capacity = capacity
6        self.stacks = []
7        self.available = []
8
9    def push(self, val: int) -> None:
10        if self.available:
11            idx = heapq.heappop(self.available)
12            self.stacks[idx].append(val)
13            if len(self.stacks[idx]) == self.capacity:
14                return
15            heapq.heappush(self.available, idx)
16        else:
17            self.stacks.append([val])
18            heapq.heappush(self.available, len(self.stacks) - 1)
19
20    def pop(self) -> int:
21        while self.stacks and not self.stacks[-1]:
22            self.stacks.pop()
23        if not self.stacks:
24            return -1
25        return self.stacks[-1].pop()
26
27    def popAtStack(self, index: int) -> int:
28        if 0 <= index < len(self.stacks) and self.stacks[index]:
29            plate = self.stacks[index].pop()
30            if len(self.stacks[index]) < self.capacity:
31                heapq.heappush(self.available, index)
32            return plate
33        return -1

Complexity note: The time complexity is O(log n) for push and pop operations due to the use of a priority queue to manage available stacks. Space complexity remains O(n) for storing the plates in stacks.

  • 1Using a priority queue helps efficiently manage available stacks.
  • 2Direct access to specific stacks allows for targeted operations.

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