- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 64 lines of Python from the credited upstream file design-order-management-system.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234567 8import collections9 10 1112class OrderManagementSystem(object):13 14 def __init__(self):15 self.__orders = {}16 self.__type_price = collections.defaultdict(list)17 18 19 def addOrder(self, orderId, orderType, price):20 """21 :type orderId: int22 :type orderType: str23 :type price: int24 :rtype: None25 """26 self.__orders[orderId] = [orderType, price, len(self.__type_price[orderType, price])]27 self.__type_price[orderType, price].append(orderId)28 29 30 def modifyOrder(self, orderId, newPrice):31 """32 :type orderId: int33 :type newPrice: int34 :rtype: None35 """36 orderType = self.__orders[orderId][0]37 self.cancelOrder(orderId)38 self.addOrder(orderId, orderType, newPrice)39 40 41 def cancelOrder(self, orderId):42 """43 :type orderId: int44 :rtype: None45 """46 orderType, price, i = self.__orders[orderId]47 arr = self.__type_price[orderType, price]48 self.__orders[arr[-1]][2] = i49 arr[i], arr[-1] = arr[-1], arr[i]50 arr.pop()51 if not self.__type_price[orderType, price]:52 del self.__type_price[orderType, price]53 del self.__orders[orderId]54 55 56 def getOrdersAtPrice(self, orderType, price):57 """58 :type orderType: str59 :type price: int60 :rtype: List[int]61 """62 return self.__type_price.get((orderType, price), [])63 64