Bird
Raised Fist0
DSA Javascriptprogramming~30 mins

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

Choose your learning style10 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 recent 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 an array called prices with the exact values: [100, 80, 60, 70, 60, 75, 85]
Create an empty array called span to store the span values
Create an empty array called stack to use as a stack for indices
Use a for loop with variable i to iterate over prices
Inside the loop, use a while loop to pop from stack while prices[stack[stack.length - 1]] <= prices[i]
Calculate the span for each day and store it in span[i]
Print the span array as a space-separated string
💡 Why This Matters
🌍 Real World
Stock analysts use the stock span problem to understand how long a stock price has been rising or stable, which helps in making investment decisions.
💼 Career
This problem teaches stack usage, which is a fundamental data structure concept useful in many software engineering roles, especially those involving algorithms and data processing.
Progress0 / 4 steps
1
Create the prices array
Create an array called prices with these exact values: [100, 80, 60, 70, 60, 75, 85]
DSA Javascript
Hint

Use const prices = [100, 80, 60, 70, 60, 75, 85]; to create the array.

2
Create the span and stack arrays
Create an empty array called span and an empty array called stack
DSA Javascript
Hint

Use const span = []; and const stack = []; to create empty arrays.

3
Calculate the stock span using a stack
Use a for loop with variable i to iterate over prices. Inside the loop, use a while loop to pop from stack while prices[stack[stack.length - 1]] <= prices[i]. Then calculate the span for day i and store it in span[i]. Finally, push i onto stack.
DSA Javascript
Hint

Use a for loop to go through each price. Use a while loop to pop indices from stack while the price at the top of the stack is less than or equal to the current price. Calculate the span as i + 1 if stack is empty, else i - stack[stack.length - 1]. Push i onto the stack.

4
Print the span array
Print the span array as a space-separated string using console.log
DSA Javascript
Hint

Use console.log(span.join(' ')) to print the span array separated by spaces.

Practice

(1/5)
1. What does the Stock Span Problem calculate for each day in a list of stock prices?
easy
A. The number of consecutive days before the current day with a price less than or equal to the current day's price
B. The maximum stock price in the entire list
C. The minimum stock price in the entire list
D. The difference between the current day's price and the previous day's price

Solution

  1. Step 1: Understand the problem definition

    The Stock Span Problem finds how many consecutive days before today had prices less than or equal to today's price.
  2. Step 2: Clarify what is calculated for each day

    For each day, it counts days backward until a higher price is found or start is reached.
  3. Final Answer:

    The number of consecutive days with price less or equal to current day -> Option A
  4. Quick Check:

    Span counts consecutive lower/equal prices before today [OK]
Hint: Span counts days with prices ≤ current day price [OK]
Common Mistakes:
  • Confusing span with max or min price
  • Thinking span is price difference
  • Ignoring consecutive days condition
2. Which of the following JavaScript code snippets correctly initializes an empty stack for solving the Stock Span Problem?
easy
A. const stack = 0;
B. const stack = {};
C. const stack = [];
D. const stack = null;

Solution

  1. Step 1: Identify the correct data structure for stack

    In JavaScript, a stack is usually implemented as an array to use push and pop methods.
  2. Step 2: Check initialization syntax

    An empty array is initialized with [] which is correct for a stack.
  3. Final Answer:

    const stack = []; -> Option C
  4. Quick Check:

    Stack uses array [] in JavaScript [OK]
Hint: Use array [] to create stack in JavaScript [OK]
Common Mistakes:
  • Using object {} instead of array
  • Assigning null or number instead of array
  • Forgetting to initialize stack before use
3. What is the output of the stock span array for the prices [100, 80, 60, 70, 60, 75, 85] using the Stock Span Problem algorithm?
medium
A. [7, 6, 5, 4, 3, 2, 1]
B. [1, 2, 3, 4, 5, 6, 7]
C. [1, 1, 1, 1, 1, 1, 1]
D. [1, 1, 1, 2, 1, 4, 6]

Solution

  1. Step 1: Calculate span for each price

    Day 0: 100 -> span=1 (no previous days)
    Day 1: 80 < 100 -> span=1
    Day 2: 60 < 80 -> span=1
    Day 3: 70 > 60 -> span=2 (includes day 2)
    Day 4: 60 < 70 -> span=1
    Day 5: 75 > 60, 70, 60 -> span=4 (days 4,3,2,1)
    Day 6: 85 > 75, 70, 60, 80 -> span=6 (days 5,3,2,1,0)
  2. Step 2: Write the span array

    The spans are [1, 1, 1, 2, 1, 4, 6].
  3. Final Answer:

    [1, 1, 1, 2, 1, 4, 6] -> Option D
  4. Quick Check:

    Span array matches calculated values [OK]
Hint: Count consecutive previous days with price ≤ current [OK]
Common Mistakes:
  • Counting all previous days instead of consecutive
  • Mixing up greater and less conditions
  • Incorrectly including days with higher prices
4. Identify the error in the following JavaScript code snippet for the Stock Span Problem:
function calculateSpan(prices) {
  const stack = [];
  const span = [];
  for (let i = 0; i < prices.length; i++) {
    while (stack.length > 0 && prices[stack[stack.length - 1]] <= prices[i]) {
      stack.pop();
    }
    span[i] = stack.length === 0 ? i + 1 : i - stack[stack.length - 1];
    stack.push(i);
  }
  return span;
}
medium
A. The span calculation formula is incorrect; it should be i + stack[stack.length - 1]
B. There is no error; the code correctly calculates the stock span
C. The stack should store prices, not indices
D. The comparison operator in while loop should be <= instead of <

Solution

  1. Step 1: Analyze the while loop condition

    The loop pops indices while the price at top index is less than or equal to current price, which is correct for span calculation.
  2. Step 2: Check span calculation formula

    If stack is empty, span is i+1 (all previous days), else difference between current index and top index in stack, which is correct.
  3. Step 3: Verify stack usage

    Stack stores indices, which is standard to access prices array correctly.
  4. Final Answer:

    There is no error; the code correctly calculates the stock span -> Option B
  5. Quick Check:

    Code matches standard stock span algorithm [OK]
Hint: Stack stores indices; span formula uses index difference [OK]
Common Mistakes:
  • Changing < to <= breaks correct span logic
  • Storing prices instead of indices causes wrong indexing
  • Incorrect span formula leads to wrong results
5. Given the stock prices array [10, 4, 5, 90, 120, 80], how would the Stock Span Problem algorithm change if we want to find the span of days with prices strictly less than the current day's price (not less than or equal)? What is the resulting span array?
hard
A. [1, 1, 2, 4, 5, 1]
B. [1, 1, 2, 3, 4, 1]
C. [1, 1, 1, 4, 5, 1]
D. [1, 2, 3, 4, 5, 6]

Solution

  1. Step 1: Understand the strict less than condition

    Change the comparison in the algorithm from ≤ to <, so only days with price strictly less count towards span.
  2. Step 2: Calculate spans with strict less than

    Day 0: 10 -> span=1
    Day 1: 4 < 10 -> span=1
    Day 2: 5 > 4 -> span=2 (days 1 and 2)
    Day 3: 90 > 5,4,10 -> span=4 (days 0,1,2,3)
    Day 4: 120 > 90 -> span=5 (days 0 to 4)
    Day 5: 80 < 120 -> span=1
  3. Final Answer:

    [1, 1, 2, 4, 5, 1] -> Option A
  4. Quick Check:

    Strict less than span matches [1,1,2,4,5,1] [OK]
Hint: Use < instead of ≤ in comparison for strict span [OK]
Common Mistakes:
  • Not changing comparison operator correctly
  • Counting equal prices in span incorrectly
  • Miscounting consecutive days with strict condition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard