3815. Design Auction System
Medium41.8% acceptance14,722 / 35,193 submissions
Asked by 1 company
Topics
You are asked to design an auction system that manages bids from multiple users in real time.
Each bid is associated with a userId, an itemId, and a bidAmount.
Implement the AuctionSystem class:
AuctionSystem(): Initializes theAuctionSystemobject.void addBid(int userId, int itemId, int bidAmount): Adds a new bid foritemIdbyuserIdwithbidAmount. If the sameuserIdalready has a bid onitemId, replace it with the newbidAmount.void updateBid(int userId, int itemId, int newAmount): Updates the existing bid ofuserIdforitemIdtonewAmount. It is guaranteed that this bid exists.void removeBid(int userId, int itemId): Removes the bid ofuserIdforitemId. It is guaranteed that this bid exists.int getHighestBidder(int itemId): Returns theuserIdof the highest bidder foritemId. If multiple users have the same highestbidAmount, return the user with the highestuserId. If no bids exist for the item, return -1.
Example 1:
Input:
["AuctionSystem", "addBid", "addBid", "getHighestBidder", "updateBid", "getHighestBidder", "removeBid", "getHighestBidder", "getHighestBidder"]
[[], [1, 7, 5], [2, 7, 6], [7], [1, 7, 8], [7], [2, 7], [7], [3]]
Output:
[null, null, null, 2, null, 1, null, 1, -1]
Explanation
AuctionSystem auctionSystem = new AuctionSystem(); // Initialize the Auction systemauctionSystem.addBid(1, 7, 5); // User 1 bids 5 on item 7
auctionSystem.addBid(2, 7, 6); // User 2 bids 6 on item 7
auctionSystem.getHighestBidder(7); // return 2 as User 2 has the highest bid
auctionSystem.updateBid(1, 7, 8); // User 1 updates bid to 8 on item 7
auctionSystem.getHighestBidder(7); // return 1 as User 1 now has the highest bid
auctionSystem.removeBid(2, 7); // Remove User 2's bid on item 7
auctionSystem.getHighestBidder(7); // return 1 as User 1 is the current highest bidder
auctionSystem.getHighestBidder(3); // return -1 as no bids exist for item 3
Constraints:
1 <= userId, itemId <= 5 * 1041 <= bidAmount, newAmount <= 109- At most
5 * 104total calls toaddBid,updateBid,removeBid, andgetHighestBidder. - The input is generated such that for
updateBidandremoveBid, the bid from the givenuserIdfor the givenitemIdwill be valid.
Hints
Hint 1
Maintain a map from
itemId to its active bids.Hint 2
For each item, use a data structure ordered by
(bidAmount, userId) to get the highest bidder efficiently.Hint 3
On
addBid or updateBid, remove the old entry (if any) and insert the new one.Hint 4
On
removeBid, delete the corresponding entry; return the top element for getHighestBidder.