0
0
DSA Pythonprogramming~30 mins

Stock Span Problem Using Stack in DSA Python - Build from Scratch

Choose your learning style9 modes available
Stock Span Problem Using Stack
📖 Scenario: You are working as a stock analyst. You want to find out how many consecutive days before today the stock price was less than or equal to today's price. This helps in understanding the stock's performance trend.
🎯 Goal: Build a program that calculates the stock span for each day using a stack. The stock span is the number of consecutive days before the current day where the stock price was less than or equal to the current day's price.
📋 What You'll Learn
Create a list called prices with the exact values: [100, 80, 60, 70, 60, 75, 85]
Create an empty list called span to store the span values
Use a stack implemented as a list called stack to help calculate spans
Use a for loop with variable i to iterate over the indices of prices
Inside the loop, use a while loop to pop from stack while the top of the stack points to a price less than or equal to prices[i]
Calculate the span for each day and append it to span
Print the span list at the end
💡 Why This Matters
🌍 Real World
Stock analysts use the stock span problem to understand how long a stock price has been rising or stable, helping in making investment decisions.
💼 Career
This problem teaches stack usage, which is important in many software engineering tasks like parsing, undo operations, and managing function calls.
Progress0 / 4 steps
1
Create the list of stock prices
Create a list called prices with these exact values: [100, 80, 60, 70, 60, 75, 85]
DSA Python
Hint

Use square brackets to create a list and separate values with commas.

2
Create the span list and stack
Create an empty list called span and an empty list called stack to use as a stack
DSA Python
Hint

Use [] to create empty lists.

3
Calculate the stock span using a stack
Use a for loop with variable i to iterate over the indices of prices. Inside the loop, use a while loop to pop from stack while stack is not empty and prices[stack[-1]] <= prices[i]. Then calculate the span for day i as i + 1 if stack is empty, else i - stack[-1]. Append the span to span and push i onto stack.
DSA Python
Hint

Use range(len(prices)) to loop over indices. Use stack[-1] to get the top of the stack.

4
Print the span list
Print the span list to display the stock span for each day
DSA Python
Hint

Use print(span) to show the result.