We want to find, for each day, how many consecutive days up to and including today had stock prices less than or equal to today's price. We use a stack to remember days with higher prices to quickly find the span.
Analogy: Imagine a line of people with different heights. For each person, you count how many consecutive people up to and including them (going backwards) are shorter or equal in height until you find a taller person. The stack helps you remember the taller people so you don't check everyone again.
Prices: [100] [80] [60] [70] [60] [75] [85]
Index: 0 1 2 3 4 5 6
Stack: Top -> [index of days with higher price]
Span: [1] [1] [1] [2] [1] [4] [6]
Dry Run Walkthrough
Input: prices: [100, 80, 60, 70, 60, 75, 85]
Goal: Calculate the stock span for each day, which is how many consecutive days up to and including the current day had price less than or equal to current day's price
Step 1: Start with day 0, price 100, stack empty, push day 0
Stack: [0]
Span: [1]
Why: First day always has span 1 because no previous days
Step 2: Day 1, price 80, top of stack day 0 price 100 > 80, push day 1
Stack: [0, 1]
Span: [1, 1]
Why: Price 80 is less than 100, so span is 1
Step 3: Day 2, price 60, top stack day 1 price 80 > 60, push day 2
Stack: [0, 1, 2]
Span: [1, 1, 1]
Why: Price 60 less than 80, span 1
Step 4: Day 3, price 70, pop day 2 (60 <= 70), now top day 1 price 80 > 70, push day 3
Stack: [0, 1, 3]
Span: [1, 1, 1, 2]
Why: Popped day 2 (60 <= 70); span = 2 (days 2 and 3)
Step 5: Day 4, price 60, top day 3 price 70 > 60, push day 4
Stack: [0, 1, 3, 4]
Span: [1, 1, 1, 2, 1]
Why: Price 60 less than 70, span 1
Step 6: Day 5, price 75, pop day 4 (60 <= 75), pop day 3 (70 <= 75), top day 1 price 80 > 75, push day 5
Stack: [0, 1, 5]
Span: [1, 1, 1, 2, 1, 4]
Why: Popped days 4 and 3; span = 4 (days 2, 3, 4, 5)
Step 7: Day 6, price 85, pop day 5 (75 <= 85), pop day 1 (80 <= 85), top day 0 price 100 > 85, push day 6
Stack: [0, 6]
Span: [1, 1, 1, 2, 1, 4, 6]
Why: Popped days 5 and 1; span = 6 (days 1, 2, 3, 4, 5, 6)
Result:
Final span array: [1, 1, 1, 2, 1, 4, 6]
Annotated Code
DSA C
#include <stdio.h>#include <stdlib.h>
// Stack structure to hold indices
typedef struct Stack {
int *arr;
int top;
int capacity;
} Stack;
// Create stack
Stack* createStack(int capacity) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->arr = (int*)malloc(capacity * sizeof(int));
return stack;
}
// Check if stack is empty
int isEmpty(Stack *stack) {
return stack->top == -1;
}
// Push to stack
void push(Stack *stack, int val) {
stack->arr[++stack->top] = val;
}
// Pop from stack
int pop(Stack *stack) {
return stack->arr[stack->top--];
}
// Peek top of stack
int peek(Stack *stack) {
return stack->arr[stack->top];
}
// Calculate stock span
void calculateSpan(int prices[], int n, int span[]) {
if (n == 0) return; // handle empty array gracefully
Stack *stack = createStack(n);
// First day span is always 1
span[0] = 1;
push(stack, 0); // push index 0for (int i = 1; i < n; i++) {
// Pop indices while price at stack top <= current price
while (!isEmpty(stack) && prices[peek(stack)] <= prices[i]) {
pop(stack); // remove smaller or equal prices
}
// If stack empty, span is i+1else difference
span[i] = isEmpty(stack) ? (i + 1) : (i - peek(stack));
push(stack, i); // push current index
}
free(stack->arr);
free(stack);
}
int main() {
int prices[] = {100, 80, 60, 70, 60, 75, 85};
int n = sizeof(prices) / sizeof(prices[0]);
int span[n];
calculateSpan(prices, n, span);
for (int i = 0; i < n; i++) {
printf("%d ", span[i]);
}
printf("\n");
return0;
}
span[0] = 1;
push(stack, 0);
Initialize first day span and push its index
while (!isEmpty(stack) && prices[peek(stack)] <= prices[i]) {
pop(stack);
}
Pop indices with prices less or equal to current price to find last higher price
span[i] = isEmpty(stack) ? (i + 1) : (i - peek(stack));
Calculate span based on distance to last higher price or whole range if none
push(stack, i);
Push current day index for future comparisons
OutputSuccess
1 1 1 2 1 4 6
Complexity Analysis
Time: O(n) because each element is pushed and popped at most once
Space: O(n) for the stack and span array to store indices and results
vs Alternative: Naive approach is O(n^2) by checking all previous days for each day, stack reduces it to O(n)
Edge Cases
Empty price array
No spans calculated, function handles gracefully
DSA C
if (n == 0) return; in calculateSpan
All prices equal
Span increases by 1 each day because all previous prices are <= current
DSA C
while (!isEmpty(stack) && prices[peek(stack)] <= prices[i]) { pop(stack); }
Strictly decreasing prices
Span is always 1 because no previous price is less or equal
DSA C
while condition fails immediately, span[i] = 1
When to Use This Pattern
When asked to find how many previous consecutive elements satisfy a condition relative to current, use a stack to track indices for O(n) solution.
Common Mistakes
Mistake: Not popping all smaller or equal prices from stack before calculating span Fix: Use a while loop to pop until top price is greater than current
Mistake: Calculating span as difference between indices without checking if stack is empty Fix: Check if stack is empty; if yes, span is current index + 1
Summary
Calculates how many consecutive days up to and including the current day had stock prices less than or equal to current day's price using a stack.
Use when you need to find spans or counts of consecutive elements satisfying a condition efficiently.
The key is to use a stack to remember indices of days with higher prices to quickly find the span.
Practice
(1/5)
1. What does the Stock Span Problem calculate for each day in a list of stock prices?
easy
A. The maximum stock price in the entire list
B. The number of consecutive days before the current day with a price less than or equal to the current day's price
C. The difference between the highest and lowest stock price
D. The total sum of stock prices up to the current day
Solution
Step 1: Understand the problem definition
The Stock Span Problem finds how many consecutive previous days had stock prices less than or equal to the current day's price.
Step 2: Identify what is calculated for each day
For each day, it counts the number of consecutive days before it with prices not greater than the current day's price.
Final Answer:
The number of consecutive days with price less or equal to current day -> Option B
Quick Check:
Span counts consecutive smaller/equal prices [OK]
Hint: Span counts consecutive days with price ≤ current day price [OK]
Common Mistakes:
Confusing span with maximum price
Calculating total sum instead of span
Counting days with price greater than current
2. Which of the following C code snippets correctly initializes an empty stack for solving the Stock Span Problem?
easy
A. int stack[100]; int top = -1;
B. int stack[] = {0}; int top = 0;
C. int *stack; top = NULL;
D. stack = new int[100]; top = -1;
Solution
Step 1: Identify correct stack initialization in C
In C, stack is usually an array with an integer top initialized to -1 to indicate empty stack.
Step 2: Check each option
int stack[100]; int top = -1; correctly declares an int array and sets top to -1. int stack[] = {0}; int top = 0; initializes top to 0 which is incorrect for empty stack. int *stack; top = NULL; uses pointer and NULL incorrectly. stack = new int[100]; top = -1; uses 'new' which is C++ syntax, not C.
Final Answer:
int stack[100]; int top = -1; -> Option A
Quick Check:
Array + top = -1 initializes empty stack in C [OK]
Hint: Use array and top = -1 for empty stack in C [OK]
Common Mistakes:
Using C++ 'new' keyword in C code
Setting top to 0 instead of -1
Using uninitialized pointers for stack
3. What is the output span array for the stock prices [100, 80, 60, 70, 60, 75, 85] using the Stock Span algorithm?
Hint: Count consecutive previous days with price ≤ current day [OK]
Common Mistakes:
Counting all previous days instead of consecutive
Ignoring equal prices in span
Miscounting span for days with fluctuating prices
4. Identify the error in the following C code snippet for Stock Span calculation:
for (int i = 0; i < n; i++) {
while (top != -1 && prices[stack[top]] <= prices[i]) {
top--;
}
span[i] = (top == -1) ? (i + 1) : (i - stack[top]);
stack[++top] = i;
}
medium
A. The condition 'top != -1' should be 'top == -1'
B. The stack push operation should be before calculating span
C. No error; code correctly calculates the stock span
D. The comparison operator in while loop should be '<' instead of '<='
Solution
Step 1: Analyze the while loop condition
The while loop pops indices from stack while the price at those indices is less than or equal to current price, which is correct for span calculation.
Step 2: Check span calculation and stack push
Span is set to i+1 if stack empty, else difference between current index and top of stack index. Then current index is pushed. This matches the standard algorithm.
Final Answer:
No error; code correctly calculates the stock span -> Option C
Quick Check:
Standard stack-based span algorithm used [OK]
Hint: Check while condition and span formula carefully [OK]
Common Mistakes:
Changing <= to < breaks span logic
Pushing before span calculation causes wrong results
Incorrect stack empty condition
5. Given stock prices [10, 4, 5, 90, 120, 80], how would the Stock Span algorithm change if we want to count days with strictly less price (not less or equal)? What is the resulting span array?
hard
A. [1, 1, 2, 4, 5, 2]
B. [1, 1, 1, 4, 5, 1]
C. [1, 1, 1, 3, 4, 1]
D. [1, 1, 2, 4, 5, 1]
Solution
Step 1: Understand change from ≤ to < in comparison
Changing from less or equal to strictly less means while popping from stack, we pop only if previous price is strictly less than current price, not equal.
Step 2: Calculate span with strict less condition
Day 0: 10, span=1 Day 1: 4, previous 10 > 4, span=1 Day 2: 5, previous 4 < 5, pop 4, span=2 Day 3: 90, previous 5 < 90, pop 5; previous 10 < 90, pop 10; stack empty, span=4 Day 4: 120, previous 90 < 120, pop 90; stack empty, span=5 Day 5: 80, previous 120 > 80, span=1 (no pop) But since we pop only if strictly less, equal prices would not pop. Here no equal prices affect.
Final Answer:
[1, 1, 2, 4, 5, 1] -> Option D
Quick Check:
Strict less changes popping condition, span updated accordingly [OK]
Hint: Use '<' instead of '<=' in while condition for strict less [OK]
Common Mistakes:
Not updating while condition correctly
Miscounting span for last day
Assuming equal prices pop stack
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.