Practice/Meta/Design a Data Structure for Stock Data Retrieval
CodingMust
You need to build a system that stores historical stock price data and allows efficient retrieval. The system should support adding stock price entries and querying them based on the stock symbol and optionally a starting date.
Implement a class StockDataSystem with the following operations:
add(stock_name, date, price): Store a stock price entry with the given stock symbol, date (in "YYYY-MM-DD" format), and price value.query(stock_name, start_date=None): Retrieve stock price records for the given symbol. If start_date is provided, return only records from that date onwards (inclusive). Results must be sorted by date in ascending chronological order. Return the data as a list of [date, price] pairs.add method should store stock price data efficientlyquery method with only a stock name should return all records for that stock sorted by datequery method with both stock name and start date should return only records on or after the start date, sorted by dateExample 1:
` stocks = StockDataSystem() stocks.add("AAPL", "2023-01-15", 150.50) stocks.add("AAPL", "2023-01-10", 148.20) stocks.add("AAPL", "2023-01-20", 152.00) result = stocks.query("AAPL")
Output: [["2023-01-10", 148.20], ["2023-01-15", 150.50], ["2023-01-20", 152.00]] Explanation: All AAPL records are returned in ascending date order. `
Example 2:
` stocks = StockDataSystem() stocks.add("MSFT", "2023-02-01", 250.00) stocks.add("MSFT", "2023-02-05", 255.00) stocks.add("MSFT", "2023-02-10", 260.00) result = stocks.query("MSFT", "2023-02-05")
Output: [["2023-02-05", 255.00], ["2023-02-10", 260.00]] Explanation: Only records from 2023-02-05 onwards are returned. `
Example 3:
` stocks = StockDataSystem() stocks.add("TSLA", "2023-03-15", 200.00) result = stocks.query("NVDA")
Output: [] Explanation: No records exist for NVDA, so an empty list is returned. `