Master the Stock Span Problem by 3 Easy Steps in Python
Tags: programming, career, interview, algorithms
Published: 2024-06-21 03:27:54

In intermediate-level interviews, candidates are often asked to solve problems related to share prices, such as the Stock Span Problem. The challenge involves calculating the span of share prices over a series of days, which measures how many consecutive days the price of a share has been less than or equal to its price on the current day.


![Master the Stock Span Problem by 3 Easy Steps in Python by interviewspreparation.com](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c77u7j5a2g4i6vtwagrt.jpg)

## Go ahead and check them out before going to your interview!

[Master the Stock Span Problem by 3 Easy Steps in Python](https://interviewspreparation.com/the-stock-span-problem-in-python/)
[Find the largest sum subarray using Kadanes Algorithm](https://interviewspreparation.com/finding-the-largest-sum-subarray-using-kadanes-algorithm/)
[Mastering Object-Oriented Programming in C++](https://interviewspreparation.com/understanding-object-oriented-programming-oop-in-cpp/)
[Palindrome Partitioning A Comprehensive Guide](https://interviewspreparation.com/palindrome-partitioning-a-comprehensive-guide/)
[what is parameter in coding and what is the deference between param and argument in programming] (https://interviewspreparation.com/what-is-a-parameter-in-programming/)
[how to inverse a matrix in c#](https://interviewspreparation.com/how-to-inverse-a-matrix-in-csharp/) 

## Understand the Stock Span Problem
Ready to learn a new algorithm? I hope your interviews are going well. Let’s begin with the crucial first step: understanding what stock span means.

In the Stock Span Problem, you are given an array of daily share prices. The span of a share’s price on a given day is defined as the maximum number of consecutive days just before the given day for which the price of the share on the current day is less than or equal to its price on the given day.

Feeling confused? Don’t worry, I have provided a [real-world example to explain how the stock span algorithm works](https://interviewspreparation.com/the-stock-span-problem-in-python/) at this page.

## Implementing the Stock Span Solution in Python
### Step 1: Initialize Variables
First, create the required variables: a list to store the span for each day and a stack to help with the calculations.

```
def calculateSpan(prices, n):
    span = [0] * n  # Array to store the span values
    stack = []      # Stack to store indices
```

### Step 2: Calculate Span Using a Stack
Iterate through each price, calculate the span using the stack, and update the span array.

```
def calculateSpan(prices, n):
    span = [0] * n
    stack = []

    for i in range(n):
        while stack and prices[stack[-1]] <= prices[i]:
            stack.pop()

        if not stack:
            span[i] = i + 1
        else:
            span[i] = i - stack[-1]

        stack.append(i)

    return span
```

### Step 3: Finalizing the Solution
Test the function with example inputs to ensure it works as expected.

```
# Example usage:
prices = [100, 80, 60, 70, 60, 75, 85]
n = len(prices)
print(calculateSpan(prices, n))  # Output: [1, 1, 1, 2, 1, 4, 6]
```
## Summarizing the Stock Span Problem Solution
The Stock Span Problem involves calculating the span of stock prices for each day in an efficient manner. Using a stack to keep track of indices allows us to solve the problem in O(N) time complexity, which is optimal for handling large input sizes.

By following these steps, you can effectively solve the Stock Span Problem in Python and be well-prepared for related interview questions.