Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

How to Solve Stock Span Problem on LeetCode

The Stock Span Problem is a classic application of the monotonic stack, often asked to test your ability to reason about "previous greater" relationships in arrays.

Leetcode

Problem Statement

Given a list of daily stock prices, return the span of stock’s price for all days. The span is the number of consecutive days before today where the price was less than or equal to today’s price.

Example:

Input: prices = [100, 80, 60, 70, 60, 75, 85] Output: [1, 1, 1, 2, 1, 4, 6]

Why This Problem Matters for Interviews

This problem:

  • Reinforces monotonic stack techniques
  • Highlights your understanding of array-index relationships
  • Prepares you for similar "next/previous greater" problems

Stack-Based Approach (Optimal)

Track indices of prices with a stack, pop until the stack top is greater than current price.

Time Complexity: O(n)
Space Complexity: O(n)

def calculateSpan(prices: list[int]) -> list[int]: stack = [] span = [0] * len(prices) for i, price in enumerate(prices): while stack and prices[stack[-1]] <= price: stack.pop() span[i] = i + 1 if not stack else i - stack[-1] stack.append(i) return span

Key Interview Talking Points

  • Why a stack is better than nested loops for span calculation
  • The role of indices vs values in the stack
  • Monotonic property and span updates
  • Handling the first day/element

Big O Complexity Recap

ApproachTime ComplexitySpace Complexity
StackO(n)O(n)

Pro Interview Tips

  • Step through the stack on sample input.
  • Explain when and why stack elements are popped.
  • Practice with test cases

Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2025 Stealth Interview ™All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy