Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Stock Price Fluctuation

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2034" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given a stream of records about a particular stock. Each record contains a timestamp and the corresponding price of the stock at that timestamp. Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream correcting the price of the previous wrong record. Design an algorithm that: Updates the price of the stock at a particular timestamp, correcting the price from any previous records at the timestamp. Finds the latest price of the stock based on the current records. The latest price is the price at the latest timestamp recorded. Finds the maximum price the stock has been based on the current records. Finds the minimum price the stock has been based on the current records. Implement the StockPrice class: StockPrice() Initializes the object with no price records. void update(int timestamp, int price) Updates the price of the stock at the given timestamp. int current() Returns the latest price of the stock. int maximum() Returns the maximum price of the stock. int minimum() Returns the minimum price of the stock. Example 1: Input ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []] Output [null, null, null, 5, 10, null, 5, null, 2] Explanation StockPrice stockPrice = new StockPrice(); stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10]. stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5]. stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5. stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1. stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3. // Timestamps are [1,2] with corresponding prices [3,5]. stockPrice.maximum(); // return 5, the maximum price is 5 after the correction. stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2]. stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4. Constraints: 1 <= timestamp, price <= 109 At most 105 calls will be made in total to update, current, maximum, and minimum. current, maximum, and minimum will be called only after update has been called at least once.

Explanation

Here's a breakdown of the optimal approach, followed by the Python code:

  • Timestamp-Price Map: Use a dictionary (hash map) to store the timestamp-price mapping. This allows for O(1) update and retrieval of prices by timestamp.
  • Latest Price Tracking: Maintain the latest timestamp and its corresponding price as separate variables for quick current() retrieval.
  • Sorted Data Structures for Min/Max: Use two sorted data structures to maintain the prices, along with their frequencies. A SortedList from the sortedcontainers library (or a multiset implemented with two heaps) allows efficient retrieval of minimum and maximum prices, as well as updating the frequency of prices when the price for the same timestamp is updated.

  • Runtime Complexity: update: O(log N), current: O(1), maximum: O(1), minimum: O(1) where N is the number of unique prices. Storage Complexity: O(N) where N is the number of updates.

Code

    from sortedcontainers import SortedList

class StockPrice:

    def __init__(self):
        self.price_map = {}  # timestamp: price
        self.latest_timestamp = 0
        self.latest_price = 0
        self.prices = SortedList() # store prices for max and min


    def update(self, timestamp: int, price: int) -> None:
        if timestamp in self.price_map:
            old_price = self.price_map[timestamp]
            self.prices.remove(old_price)

        self.price_map[timestamp] = price
        self.prices.add(price)

        if timestamp >= self.latest_timestamp:
            self.latest_timestamp = timestamp
            self.latest_price = price


    def current(self) -> int:
        return self.latest_price


    def maximum(self) -> int:
        return self.prices[-1]


    def minimum(self) -> int:
        return self.prices[0]

More from this blog

C

Chatmagic blog

2894 posts