AlgoTales · Roadmap

Stock span

Intermediate · 10 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The stock span of a day is how many days in a row, ending today, had a price no higher than today. It shows how strong today's price is against its recent past. A stack of earlier higher prices gives every day's span in one pass.

Practical use cases

  • Web app: Strength badge on a mandi price chart. A market-price site shows a badge such as "best in 9 days" next to today's mango price. Counting backward every day would be slow for many crops and years. A stack of earlier higher prices lets each day compute its streak in one quick step, so the chart builds for all crops together.
  • Web app: Sports and fitness streaks. A running app tells you "this is your longest run in the last 14 sessions". The same span idea finds how far back today's distance is still the highest, without checking every earlier session each time, even for people with years of workout history.
  • System: Dashboards and weather records. Weather services report "hottest day in 40 years" and analytics dashboards flag the best sales day in a long period. Both rely on the span idea, applied to very long series where scanning back each time would be far too costly.

The story: Zoya's Mango Mandi Diary

Every evening Zoya wrote down the price of a dozen mangoes at the mandi: 100, 80, 60, 70, 60, 75, 85 rupees. Her grandfather Bhaskar liked a different question each day: "For how many days, counting today and going backwards, has the price been no higher than today's?" That count is called the span.

On day 6 the price was 75. Going back: day 5 was 60, day 4 was 70, both not higher. Day 3 was 60, still lower. Day 2 was 80: higher, so stop. The span of day 6 was 4 days (days 3 to 6). Zoya could do this for each day by walking back, but it took forever with a year of data.

Then Zoya noticed that she was repeating herself: when day 6 walked back over days 5, 4 and 3, those days already knew their own spans. If she kept a stack of (price, span) pairs, with higher prices at the bottom, then today only had to pop the cheaper-or-equal days and add up their spans. The first higher price left on the stack is the wall where the span stops.

That is the classic stock span problem. It is a monotonic stack in disguise: it finds the previous greater price, and the span is simply today's position minus that position.

How to spot this problem, and where you need it

For each day you want to know how far back today's value remains the largest, a streak or record length, and counting back day by day is too slow on long histories.

Signs you need it

  • Phrases like "best in N days", "highest since", "record-breaking streak" or "stock span" appear in the requirement.
  • For each new data point you scan backward until you meet a larger one, and the scan is longer the more history you have.
  • You need the span for every day in the series, such as a chart overlay, not just today's.

Where to use it in a project

  • Price, sales and traffic dashboards labelling days as record highs or strong streaks.
  • Fitness, weather and sports apps that show "best in the last N" labels on results.
  • Analytics reports that compute a rolling strength score for each day.

The solution

Keep a stack of earlier days with their spans, holding only days with higher prices than anything after them. For each new day, set its span to one, and while the top of the stack has a price not higher than today, pop it and add its span to today's. Push today's day. Because popped days are merged into today's span, nothing is counted twice.

Payoff: Before: walking back through up to years of history for each day. After: a few quick pops per day, so the whole chart is computed in one pass.

Explain it like I am 8

Today's price is a tall building. Look back along the street: how many buildings in a row, ending with today's, are not taller than it? A smart way is to remember a short list of tall buildings. Every shorter building that today's building covers is simply removed from the list, and its count is added to today's count.

How it works, step by step

  1. Keep a stack of (price, span) pairs. Prices from bottom to top are decreasing.
  2. For each new day, start with span = 1 (today counts).
  3. While the top price is ≤ today's price, pop it and add its span to today's span.
  4. Push (today's price, span) and record the span for the day.
  5. The first higher price left on the stack is the day where the streak stopped. Nothing else needs to be re-scanned.

The code in four languages

PHP

<?php
// Stock span: for each day, how many consecutive days (ending today)
// had a price that was not higher than today's price.
function stockSpan(array $prices): array {
    $spans = [];
    $stack = [];                                     // pairs [price, span]

    foreach ($prices as $p) {
        $span = 1;                                   // today counts
        while ($stack && end($stack)[0] <= $p) {
            $span += array_pop($stack)[1];           // swallow the cheaper days' spans
        }
        $stack[] = [$p, $span];
        $spans[] = $span;
    }
    return $spans;
}

echo implode(', ', stockSpan([100, 80, 60, 70, 60, 75, 85])) . PHP_EOL;   // 1, 1, 1, 2, 1, 4, 6

JavaScript

// Stock span: for each day, how many consecutive days (ending today)
// had a price that was not higher than today's price.
function stockSpan(prices) {
  const spans = [];
  const stack = [];                                  // pairs [price, span]

  for (const p of prices) {
    let span = 1;                                    // today counts
    while (stack.length && stack[stack.length - 1][0] <= p) {
      span += stack.pop()[1];                        // swallow the cheaper days' spans
    }
    stack.push([p, span]);
    spans.push(span);
  }
  return spans;
}

console.log(stockSpan([100, 80, 60, 70, 60, 75, 85]).join(', '));   // 1, 1, 1, 2, 1, 4, 6

Java

import java.util.*;

public class Main {
    // Stock span: for each day, how many consecutive days (ending today)
    // had a price that was not higher than today's price.
    static int[] stockSpan(int[] prices) {
        int[] spans = new int[prices.length];
        Deque<int[]> stack = new ArrayDeque<>();         // pairs {price, span}

        for (int i = 0; i < prices.length; i++) {
            int p = prices[i];
            int span = 1;                                // today counts
            while (!stack.isEmpty() && stack.peek()[0] <= p) {
                span += stack.pop()[1];                  // swallow the cheaper days' spans
            }
            stack.push(new int[]{p, span});
            spans[i] = span;
        }
        return spans;
    }

    public static void main(String[] args) {
        int[] spans = stockSpan(new int[]{100, 80, 60, 70, 60, 75, 85});
        System.out.println(Arrays.toString(spans));      // [1, 1, 1, 2, 1, 4, 6]
    }
}

Go

package main

import "fmt"

type entry struct{ price, span int }

// stockSpan: for each day, how many consecutive days (ending today)
// had a price that was not higher than today's price.
func stockSpan(prices []int) []int {
	spans := make([]int, 0, len(prices))
	var stack []entry // pairs (price, span)

	for _, p := range prices {
		span := 1 // today counts
		for len(stack) > 0 && stack[len(stack)-1].price <= p {
			span += stack[len(stack)-1].span // swallow the cheaper days' spans
			stack = stack[:len(stack)-1]
		}
		stack = append(stack, entry{p, span})
		spans = append(spans, span)
	}
	return spans
}

func main() {
	fmt.Println(stockSpan([]int{100, 80, 60, 70, 60, 75, 85})) // [1 1 1 2 1 4 6]
}

Time: O(n) · Extra space: O(n). Each day is pushed once and popped at most once. Walking back for every day would be O(n²).

Watch out for

  • Forgetting that today counts, so the smallest span is 1, not 0.
  • Popping only strictly smaller prices. Equal prices are "not higher", so use <=.
  • Throwing away the popped spans instead of adding them. That would make you re-count the days you just skipped.

Quick check

  1. Prices 100, 80, 60, 70. What is the span of the last day (70)?
    • 2
    • 3
    • 1
  2. When a day is popped from the stack, what do we do with its span?
    • Ignore it
    • Add it to today's span
    • Subtract it from today's span
  3. Which structure does stock span rely on?
    • A sorted array
    • A queue
    • A monotonic stack