#3815

Design Auction System

Medium
Hash TableDesignHeap (Priority Queue)Ordered SetHash MapHeap
LeetCode ↗

Approaches

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

Intuition

Time O(log n)Space O(n)

Utilize a hash map to store bids and a max-heap to efficiently retrieve the highest bid. This allows for constant time updates and logarithmic time retrieval.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a hash map to store bids as (userId, bidAmount) pairs for each item.
  2. 2Step 2: Maintain a max-heap for each item to track the highest bid efficiently.
  3. 3Step 3: When adding/updating a bid, adjust the heap accordingly to ensure it reflects the current highest bid.
solution.py23 lines
1import heapq
2class AuctionSystem:
3    def __init__(self):
4        self.bids = {}
5        self.max_heap = {}
6
7    def addBid(self, userId, itemId, bidAmount):
8        if itemId not in self.bids:
9            self.bids[itemId] = {}
10            self.max_heap[itemId] = []
11        if userId in self.bids[itemId]:
12            self.bids[itemId][userId] = bidAmount
13        else:
14            self.bids[itemId][userId] = bidAmount
15        heapq.heappush(self.max_heap[itemId], (-bidAmount, userId))
16
17    def getHighestBidder(self, itemId):
18        while self.max_heap[itemId]:
19            bidAmount, userId = self.max_heap[itemId][0]
20            if self.bids[itemId][userId] == -bidAmount:
21                return userId
22            heapq.heappop(self.max_heap[itemId])
23        return -1

Complexity note: The complexity is logarithmic for adding bids due to the heap operations, while space complexity is linear due to storing bids and heaps.

  • 1Use of hash maps for quick access to bids
  • 2Max-heap allows efficient retrieval of highest bids

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