# Stock Span Problem

• Stock Span Problem is a financial problem.
• In this problem, we are provided with the ' n ' number of stocks with their corresponding prices.
• These prices of the stocks are daily, and we just need to compare the stock prices.
• In this stock span problem, we need to determine the number of stocks that have an equal or lesser price than the current stock until we reach the stock greater than the current stock.
• This problem is mainly asked in the interviews of Amazon and Google, and the candidate must answer this problem in the duration of time through programming.
• The term stock span is defined as the number of consecutive stocks before the current stock when the price of the prior stocks is less than or equal to the current stock's price. Let us understand in detail with the help of an example -

Suppose we have provided an array of 10 stocks; these stocks refer to the corresponding prices of the stocks daily.

Stock number Stock Prices
1 150
2 170
3 180
4 80
5 85
6 90
7 100
8 110
9 75
10 95

Now, we will store all these stock prices in an array named as -

A = { 150 , 170 , 180 , 80 , 85 , 90 , 100 , 110 , 75 , 95 }

Now, manually let us find out the result -

1. First of all, compare the index 0 elements with the previous element, as we know that there is nothing behind the index 0 except a garbage value, so in short, we do not need to compare and simply print 1 for index 0.

2. For index 1, we will compare the value of index 1 with itself and the previous one, i.e., from the value present at index 0.

170 <= 170 ; True

150 <= 170 ; True

We will print 2 for index 1.

3. For index 2, we will compare the value of index 2 with itself and the previous indexes, i.e., from value present at index 0 and 1, until we find the greater value than the value present index 2.

180 <= 180 ; True

170 <= 180 ; True

150 <= 180 ; True

We will print 3 for index 2.

4. For index 3, we will compare the value of index 3 with itself and the previous indexes, i.e., from value present at index 0, 1, and 2, until we find the greater value than the value present index 3.

80 <= 80 ; True

180 <= 80 ; False

We will print 1 for index 3.

5. For index 4, we will compare the value of index 4 with itself and the previous indexes, i.e., from value present at index 0, 1, 2, and 3, until we find the greater value than the value present index 4.

85 <= 85 ; True

80 <= 85 ; True

180 <= 85 ; False

We will print 2 for index 4.

6. For index 5, we will compare the value of index 5 with itself and the previous indexes, i.e., from value present at index 0, 1, 2, 3, and 4, until we find the greater value than the value present index 5.

90 <= 90 ; True

85 <= 90 ; True

80 <= 90 ; True

180 <= 90 ; False

We will print 3 for index 5.

7. For index 6, we will compare the value of index 6 with itself and the previous indexes, i.e., from value present at index 0, 1, 2,3 4, 5, until we find the greater value than the value present index 6.

100 <= 100 ; True

90 <= 100 ; True

85 <= 100 ; True

80 <= 100 ; True

180 <= 100 ; False

We will print 4 for index 6.

8. For index 7, we will compare the value of index 7 with itself and the previous indexes, i.e., from value present at index 0, 1, 2, 3, 4, 5, 6, until we find the greater value than the value present index 7.

110 <= 110 ; True

100 <= 110 ; True

90 <= 110 ; True

85 <= 110 ; True

80 <= 110 ; True

180 <= 110 ; False

We will print 5 for index 7.

9. For index 8, we will compare the value of index 8 with itself as well as the previous indexes, i.e., from value present at index 0, 1, 2, 3, 4, 5, 6, 7, until we find the greater value than the value present index 8.

75 <= 75 ; True

110 <= 75 ; False

We will print 1 for index 8.

10. For index 9, we will compare the value of index 9 with itself as well as the previous indexes, i.e., from value present at index 0, 1, 2, 3, 4, 5, 6, 7, 8, until we find the greater value than the value present index 9.

95 <= 95 ; True

75 <= 95 ; True

110 <= 95 ; False

We will print 2 for index 9.

Hence final output will be -

Output = { 1 , 2 , 3 , 1 , 2 , 3 , 4 , 5 , 1 , 2 }

Here we can observe that for an nth term, we require n comparisons, n-1 for previous ones, and 1 for itself; hence total n comparisons require nth term.

## Methods to solve Stock Span Problem -

1. By using the Brute force approach, an inefficient method.
2. By using Stack, an efficient method
3. By using multiple stacks
4. Linear complexity method, without using Stack

Let us start solving this Stock span problem using these methods.

## Method # 1 Brute Force approach, an inefficient method -

Although this method is not so efficient, it is very easy to implement to solve any problem. If you want to understand the basic criteria, you first implement any program using the Brute force method. Once you have succeeded in making the program, then try to find the other best alternative to solve the given problem, in much more efficient way, whose performance is also better and time complexity is also less then this method.

Let us discuss the stock span problem using this method:

As we have already seen, the working of the stock span problem is to find the number of stocks, which are less than or equal to the target stock. Thus, we called it finding the Span of that stock.

### Algorithm to implement Brute force method to solve this problem -

Step 1 - Take an array named ' Stockprice ' from the user of ' n ' elements; here, elements refer to the stock, and this array contains the corresponding prices of the stocks. Also, make another array named ' span ', which stores the span values for each of the corresponding stocks.

Step 2 - Make a function named ' Calspan ', this function targets to calculate the Span or number of stocks whose prices are less than or equal to the current stock until we reach the value greater than the current value.

Step 3 - Calspan function will calculate the Span for each of the stocks.

Step 4 - From the main function, pass Stockprice array, number of elements, and an array named Span, which stores the values of Span, calculated in the Calspan function.

Step 5 - In the Calspan function, initialize the value of Span [ 0 ] = 1, as we know that the first element of the stockprice array must have a span value equal to 1 because no price is less than its value, but it is equal to itself hence its value always starts with one.

Step 6 - Format the two loops; one loop is for pointing a particular stock price in an array stockprice, and another array is for calculating the span value for the pointing stock price.

Step 7 - The first loop will run from 1 to n - 1 since the index 0 stock price value is always one, as described above.

Step 8 - The second loop will start from n - 1, as we are comparing the values in the reverse direction of the current stock. If we get a value greater than the current stock price, we will come out of the loop and store the corresponding span value in the index ith of the span array.

Step 9 - Initialize the span [ 1 ] = 1. After that, run the second loop, which compares the current pointing stock price from the stock prices. It occurs before the current stock prices and to check whether the value of the prices occurs before and less than the current stock price or not.

Step 10 - If the stock price is less than the current stock price, then increment the value of Span by 1 at that particular index.

Step 11 - After traversing the stock price array from 1 to n - 1, print the resulting span array from the main function.

Step 12 - Finally, we will get the desired output in the result.

### Implementation of Stock Span Problem using Method # 1 in C Programming Language

The output of the following C program for solving the Stock span problem using Method # 1 ### Implementation of Stock Span Problem using Method # 1 in C++ Programming Language

The output of the following C++ program for solving the Stock span problem using Method # 1 ### Implementation of Stock Span Problem using Method # 1 in Java Programming Language

The output of the following Java program for solving the Stock span problem using Method # 1 ### Implementation of Stock Span Problem using Method # 1 in Python Programming Language

The output of the following Java program for solving the Stock span problem using Method # 1 ### Implementation of Stock Span Problem using Method # 1 in C# Programming Language

The output of the following C# program for solving the Stock span problem using Method # 1

``` 1   1    2    4    5    1
```

After executing the program successfully in a specific programming language and following the Brute force algorithm using the nested traversal approach, we will get the proper result, i.e., finding out the span values for given stock prices daily.

Now let us analyze the running time and performance of the algorithm we are applying to get the span values for corresponding stock prices by finding the algorithm's time complexity and space complexity using in Method # 1.

### Time Complexity of Method # 1 -

For finding the time complexity, we need to observe the algorithm and analyze the time taken by a particular line for execution. We can observe that we require traversing the stock price array nested one loop in another loop; one traversal of the loop for traversing the stock prices from 1 to n - 1 stock prices, and the second loop is for comparing the stock price from previous stock prices until we get the stock price greater than the current stock price, and simultaneously incrementing the values of Span for corresponding stock prices in span array, finally in this way we require nested loop traversing. Hence time complexity will be -

T ( n ) = O ( n ).O ( n )

T ( n ) = O ( n2 )

Hence time complexity will be O ( n2 ), as we do the asymptotically rough idea that we require ' n2 ' time to solve the problem of ' n ' elements.

### Space Complexity of Method # 1 -

To find space complexity, we need to observe the program and analyze the space required to store all the variables; as we notice the program, we will observe that for storing span values of corresponding ' n ' stock prices, we require an array of ' n ' variables to store ' n ' span values.

S ( n ) = O ( n )

Hence the space complexity for above method # 1 will be O ( n ).

## Method # 2 By Using Stack, an efficient method -

This method is very efficient compared to the previous Brute force method because the time complexity in the brute force approach is O ( n2 ) due to the nested loop traversal. Still, in this stacking method, time complexity will be O ( n ). We will see it further in the analysis of the algorithm. Time complexity is also less than the previous method and this method is also known as the linear time complexity method.

Let us discuss the stock span problem using this method:

As we have already seen, the working of the stock span problem is to find the number of stocks, which are less than or equal to the target stock. Thus, we called it finding the Span of that stock.

### Algorithm to implement Stack method to solve this problem -

Step 1 - Take an array named ' Stockprice ' from a user of ' n ' elements; here, elements refer to the stock, and this array contains the corresponding prices of the stocks. Also, make another array named ' span ', which stores the span values for each of the corresponding stocks.

Step 2 - Make a function named ' Calspan ', this function targets to calculate the Span or number of stocks whose prices are less than or equal to the current stock until we reach the value greater than the current value.

Step 3 - Calspan function will calculate the Span for each of the stocks.

Step 4 - From the main function, pass Stockprice array, number of elements, and an array named Span, which stores the values of Span, calculated in the Calspan function.

Step 5 - In the Calspan function, initialize the value of Span [ 0 ] = 1, as we know that the first element of the stockprice array for day 1 must have a span value equal to 1 because no price is less than its value, but it is equal to itself hence its value always starts with one.

Step 6 - After allocating span value 1 for the stock price of day 1, then for the next stock price for further days, add this corresponding list of Span for current stock price day if the stock price of the current day is greater than or equal to the previous stock prices, then push the index of that element into the Stack.

Step 7 - Now for to calculate the span values for further days, we will use the concept of Stack, in which we would perform mainly two operations push and pop; push is used to push the data element into the Stack and pop is used to retrieve the data element out of the Stack.

Step 8 - Initially, we check the stock price corresponding to the index on the top of the Stack.

Step 9 - Compare the top stock price of the Stack with the stock price of the current day; if the current day stock price is greater or equal to the stock price of the top of the Stack, then pop this index out of stock.

Step 10 - Repeat the step 9 for the next top of the Stack until you reach the state for which the stock price of the current day is smaller than the stock price of the top of the Stack.

Step 11 - After that, calculate the span values of the corresponding stock prices by subtracting the index at the top of the Stack from the index of the current day.

Step 12 - Finally, we will get the desired output in the result.

### Implementation of Stock Span Problem using Method # 2 in C++ Programming Language

The output of the following C++ program for solving the Stock span problem using Method # 2 ### Implementation of Stock Span Problem using Method # 2 in Java Programming Language

The output of the following Java program for solving the Stock span problem using Method # 2 ### Implementation of Stock Span Problem using Method # 2 in Python Programming Language

The output of the following Python program for solving the Stock span problem using Method # 2 ### The output of the following C# program for solving the Stock span problem using Method # 2

``` 1   1    2    4    5    6
```

After executing the program successfully in a specific programming language and following the Brute force algorithm using the nested traversal approach, we will get the proper result, i.e., finding out the span values for given stock prices daily.

Now let us analyze the running time and performance of the algorithm we are applying to get the span values for corresponding stock prices by finding the algorithm's time complexity and space complexity using in Method # 2.

### Time Complexity of Method # 2 -

For finding the time complexity, we need to observe the algorithm and analyze the time taken by a particular line for execution. We can observe that we require traversing the stock price array using one loop only; traversal of the loop for traversing the stock prices from 1 to n - 1 stock prices, and inside that loop, we are using a stack data structure to hold the span values and for doing comparisons among these stock prices of different days. Hence time complexity will be -

T ( n ) = O ( n ) + C

Here, ' C ' be any constant.

T ( n ) = O ( n )

Hence time complexity will be O ( n ), as we do the asymptotically rough idea that we require ' n ' time to solve the problem of ' n ' elements.

### Space Complexity of Method # 2 -

To find space complexity, we need to observe the program and analyze the space required to store all the variables; as we notice the program, we will observe that for storing span values of corresponding ' n ' stock prices, we require an array of ' n ' variables to store ' n ' span values.

S ( n ) = O ( n )

Hence the space complexity for above method # 2 will be O ( n ).

## Method # 3 By Using Multiple Stacks -

The implementation of this method is quite different from the method 2. We will see it further in the analysis of the algorithm.

Let us discuss the stock span problem using this method:

As we have already seen, the working of the stock span problem is to find the number of stocks, which are less than or equal to the target stock. Thus, we called it finding the Span of that stock.

### Algorithm to implement Multiple Stack method to solve this problem -

Step 1 - In this method, we will use two stacks for finding the span values of the corresponding stock price of particular days.

Step 2 - Initially define the size of the stock prices so that it will remain constant throughout the program, and it will be easy to implement the logic.

Step 3 - One Stack is used to store the actual stock prices, as we compare it with previous methods; in this place, we are using an array to store stock prices, but here it is replaced by a stack data structure.

Step 4 - Another stack is used to store the Span values temporarily, and we also call this Stack a temporary Stack.

Step 5 - Using the above two stacks, we will solve this problem using push and pop operations of Stack. The remaining procedure of comparison criteria will be the same as method 2 using a single Stack.

Step 6 - At last, store the values of Span from stack 2 to an array named Span, and print the result.

Step 7 - Finally, we will get the desired output in the result.

### Implementation of Stock Span Problem using Method # 3 in C Programming Language

The output of the following C program for solving the Stock span problem using Method # 3 Now let us analyze the running time and performance of the algorithm we are applying to get the span values for corresponding stock prices by finding the algorithm's time complexity and space complexity using in M ethod # 3.

### Time Complexity of Method # 3 -

For finding the time complexity, we need to observe the algorithm and analyze the time taken by a particular line for execution. We can observe that we require two stacks for executing this stock span problem, one Stack is needed to store the stock prices of corresponding days; and another stack is needed to store the temporary values of Span, calculated by further comparisons between the stock prices, and finally, we have store these span values in an array. Hence time complexity will be -

T ( n ) = O ( n ) + C

Here ' C ' be any constant.

T ( n ) = O ( n )

Hence time complexity will be O ( n ), as we do the asymptotically rough idea that we require ' n ' time to solve the problem of ' n ' elements.

### Space Complexity of Method # 3 -

To find space complexity, we need to observe the program and analyze the space required to store all the variables; as we notice the program, we will observe that for storing span values of corresponding ' n ' stock prices, we require an array of ' n ' variables to store ' n ' span values.

S ( n ) = O ( n )

Hence the space complexity for above method # 3 will be O ( n ).

## Method # 4 Linear Complexity method, without using Stack -

This method is very efficient compared to the previous Brute force method because the time complexity in the brute force approach is O ( n2 ) due to the nested loop traversal. Still, in this stacking method, time complexity will be O ( n ), this method is different from the above three methods, but the concept of finding span values remains the same for all the methods. We will see it further in the analysis of the algorithm, and it is very easy to implement to solve any problem, in a much more efficient way, whose performance is also better; hence this method is also known as the linear time complexity method.

Let us discuss the stock span problem using this method:

As we have already seen, the working of the stock span problem is to find the number of stocks, which are less than or equal to the target stock. Thus, we called it finding the Span of that stock.

### Algorithm to implement linear-complexity method without using Stack to solve this problem -

Step 1 - Take an array named ' Stockprice ' from a user of ' n ' elements; here, elements refer to the stock, and this array contains the corresponding prices of the stocks. Also, make another array named ' span ', which stores the span values for each of the corresponding stocks.

Step 2 - Make a function named ' Calspan ', this function targets to calculate the Span or number of stocks whose prices are less than or equal to the current stock until we reach the value greater than the current value.

Step 3 - Calspan function will calculate the Span for each of the stocks.

Step 4 - From the main function, pass Stockprice array, number of elements, and an array named Span, which stores the values of Span, calculated in the Calspan function.

Step 5 - In the Calspan function, initialize the value of Span [ 0 ] = 1, as we know that the first element of the stockprice array for day 1 must have a span value equal to 1 because no price is less than its value, but it is equal to itself hence its value always starts with one.

Step 6 - After allocating span value 1 for the stock price of day 1, then for the next stock price for further days, run a loop form i = 1 to ' n - 1 ' stock prices of corresponding days inside that loop initialize one count variable with 1.

Step 7 - After that, run a while loop for the condition :

while ( i - count ) >= 0 && stockprice[ i ] >= stockprice[ i - count ] )

{

count = count + span [ i - count ] // if condition true

}

Step 8 - Outside the while loop and inside the for loop, finally set the Span [ i ] = count.

Step 9 - At last, from the main function, print the span values.

Step 10 - Finally, you will get the desired output as a result.

### Implementation of Stock Span Problem using Method # 4 in C Programming Language

The output of the following C program for solving the Stock span problem using Method # 4 ### Implementation of Stock Span Problem using Method # 4 in C++ Programming Language

The output of the following C++ program for solving the Stock span problem using Method # 4 ### Implementation of Stock Span Problem using Method # 4 in Java Programming Language

The output of the following Java program for solving the Stock span problem using Method # 4 ### Implementation of Stock Span Problem using Method # 4 in Python Programming Language

The output of the following Python program for solving the Stock span problem using Method # 4 ### Implementation of Stock Span Problem using Method # 4 in C# Programming Language

The output of the following C# program for solving the Stock span problem using Method # 4

``` 1   1    2    4    5    1
```

After executing the program successfully in a specific programming language and following the linear complexity algorithm without using Stack, we will get the proper result, i.e., finding out the span values for given stock prices daily.

Now let us analyze the running time and performance of the algorithm we are applying to get the span values for corresponding stock prices by finding the algorithm's time complexity and space complexity using in Method # 4.

### Time Complexity of Method # 4 -

For finding the time complexity, we need to observe the algorithm and analyze the time taken by a particular line for execution. We can observe that we require traversing the stock price array using one loop; for traversal of the loop for traversing the stock prices from 1 to n - 1 stock prices, and while condition loop is for comparing the stock price from previous stock prices until we get the stock price greater than the current stock price, and simultaneously incrementing the values of Span for corresponding stock prices in span array, finally in this way we require nested loop traversing. Hence time complexity will be -

T ( n ) = O ( n ) + C

T ( n ) = O ( n )

Hence time complexity will be O ( n ), as we do the asymptotically rough idea that we require ' n ' time to solve the problem of ' n ' elements.

### Space Complexity of Method # 4 -

To find space complexity, we need to observe the program and analyze the space required to store all the variables; as we notice the program, we will observe that for storing span values of corresponding ' n ' stock prices, we require an array of ' n ' variables to store ' n ' span values.

S ( n ) = O ( n )

Hence the space complexity for above method # 4 will be O ( n ).

### Feedback   