901. Online Stock Span

Dare2Solve

Dare2Solve

901. Online Stock Span
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Description

The problem is to design a data structure that efficiently handles operations like adding elements, processing them, and returning results based on specific conditions. This is often used in financial applications, where you need to process stock prices, intervals, or other sequential data in an optimized manner.

Intuition

The intuition behind solving these types of problems is to use data structures that allow efficient retrieval and modification of elements. Stacks, queues, and arrays are often useful for managing sequences where the most recent elements have a significant impact on the results.

For example, in a problem involving stock prices, the goal is to determine how many consecutive days the stock price has been less than or equal to today’s price. A stack can be used to keep track of previous prices in a way that allows for quick computation of this "span."

Approach

  1. Initialization: Define a class or function that will handle the operations. This will often involve initializing an empty data structure, such as a stack or list.

  2. Processing: Iterate over the input data (e.g., prices, intervals), applying the specific logic required by the problem. For each element, decide whether it should be added to the data structure, removed, or used in a calculation.

  3. Optimization: Use techniques like sorting, dynamic programming, or greedy algorithms to minimize the number of operations. The goal is to ensure that each element is processed in constant or logarithmic time whenever possible.

  4. Return Results: After processing the input data, return the required results, which might involve the state of the data structure or a final computed value.

Complexity

Time Complexity:

The time complexity depends on the operations performed and the data structures used. For example, using a stack to track stock prices can lead to an average time complexity of O(1) per operation, making the overall time complexity O(n) for processing n elements.

Space Complexity:

The space complexity depends on the size of the data structure used. In many cases, it is O(n), where n is the number of elements stored in the structure.

Code

C++

class StockSpanner {
public:
    vector<int> stock;

    StockSpanner() {
        stock = vector<int>();
    }

    int next(int price) {
        stock.push_back(price);
        for (int i = stock.size() - 2; i >= 0; i--) {
            if (stock[i] > price) {
                return stock.size() - 1 - i;
            }
        }
        return stock.size();
    }
};

Python

class StockSpanner:

    def __init__(self):
        self.stock = []

    def next(self, price: int) -> int:
        self.stock.append(price)
        for i in range(len(self.stock) - 2, -1, -1):
            if self.stock[i] > price:
                return len(self.stock) - 1 - i
        return len(self.stock)

Java

class StockSpanner {
    private ArrayList<Integer> stock;

    public StockSpanner() {
        stock = new ArrayList<>();
    }

    public int next(int price) {
        stock.add(price);
        for (int i = stock.size() - 2; i >= 0; i--) {
            if (stock.get(i) > price) {
                return stock.size() - 1 - i;
            }
        }
        return stock.size();
    }
}

JavaScript

var StockSpanner = function() {
    this.stock = []
};

/** 
 * @param {number} price
 * @return {number}
 */
StockSpanner.prototype.next = function(price) {
     this.stock.push(price)
    for(let i=this.stock.length-2;i>=0;i--){

        if(this.stock[i] > price){
            return this.stock.length-1 - i
        }
    }
    return this.stock.length
};