Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Stock Span Problem Using Stack in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stock Span Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Stock Span Calculation
What is the output of the stock span array after running the given code with prices [100, 80, 60, 70, 60, 75, 85]?
DSA Javascript
function calculateSpan(prices) {
  const n = prices.length;
  const span = new Array(n).fill(1);
  const stack = [];

  for (let i = 0; i < n; 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;
}

console.log(calculateSpan([100, 80, 60, 70, 60, 75, 85]));
A[1, 2, 3, 4, 5, 6, 7]
B[1, 1, 1, 2, 1, 4, 6]
C[1, 1, 1, 1, 1, 1, 1]
D[7, 6, 5, 4, 3, 2, 1]
Attempts:
2 left
💡 Hint
Remember the span counts how many consecutive days before the current day had prices less than or equal to the current price.
🧠 Conceptual
intermediate
1:30remaining
Understanding Stack Usage in Stock Span
Why do we use a stack to solve the stock span problem efficiently?
ATo keep track of indices of previous days with higher stock prices for quick span calculation.
BTo store all stock prices in sorted order for binary search.
CTo count the total number of days in the price list.
DTo reverse the array of prices before processing.
Attempts:
2 left
💡 Hint
Think about how the stack helps find the nearest previous day with a higher price.
🔧 Debug
advanced
2:00remaining
Identify the Error in Stock Span Code
What error will the following code produce when calculating stock span for prices [10, 4, 5, 90, 120, 80]? function calculateSpan(prices) { const span = []; const stack = []; for (let i = 0; i <= prices.length; i++) { while (stack.length && 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; } console.log(calculateSpan([10, 4, 5, 90, 120, 80]));
ATypeError: Cannot read property of undefined
BReferenceError: stack is not defined
COutput: [1, 1, 2, 4, 5, 1]
DSyntaxError: Unexpected token
Attempts:
2 left
💡 Hint
Check the loop boundary and array access inside the loop.
❓ Predict Output
advanced
2:00remaining
Output of Modified Stock Span with Equal Prices
What is the output of the stock span array for prices [30, 35, 35, 40, 38, 38, 42] using the standard stack-based algorithm?
DSA Javascript
function calculateSpan(prices) {
  const n = prices.length;
  const span = new Array(n).fill(1);
  const stack = [];

  for (let i = 0; i < n; 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;
}

console.log(calculateSpan([30, 35, 35, 40, 38, 38, 42]));
A[1, 2, 2, 4, 1, 2, 7]
B[1, 1, 1, 1, 1, 1, 1]
C[1, 2, 1, 4, 1, 2, 7]
D[1, 2, 3, 4, 1, 2, 7]
Attempts:
2 left
💡 Hint
Equal prices are included in the span count because the condition uses <=.
🚀 Application
expert
2:30remaining
Maximum Stock Span Value
Given the prices array [31, 41, 48, 59, 79, 79, 79, 60, 55, 70], what is the maximum value in the stock span array computed by the standard stack-based algorithm?
DSA Javascript
function calculateSpan(prices) {
  const n = prices.length;
  const span = new Array(n).fill(1);
  const stack = [];

  for (let i = 0; i < n; 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;
}

const prices = [31, 41, 48, 59, 79, 79, 79, 60, 55, 70];
const spans = calculateSpan(prices);
console.log(Math.max(...spans));
A6
B10
C7
D5
Attempts:
2 left
💡 Hint
Calculate spans carefully, especially for repeated equal prices.

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