Data Structures & AlgorithmsVery hardProduct company OA

The stock span of day i is the number of consecutive days ending at day i whose price is ≤ the price on day i. For prices [31, 27, 14, 21, 30, 18, 25, 40], what are the spans?

  1. A. 1, 1, 1, 2, 3, 1, 2, 8
  2. B. 1, 1, 1, 2, 4, 1, 2, 3
  3. C. 1, 2, 3, 4, 5, 6, 7, 8
  4. D. 1, 1, 1, 2, 4, 1, 2, 8

Correct answer: D. 1, 1, 1, 2, 4, 1, 2, 8

With a stack of indices holding decreasing prices: 21 pops 14 → span 2; 30 pops 21 and 27 → span 4 (days 27, 14, 21, 30); 25 pops 18 → span 2; 40 pops everything → span 8. '3' for day 5 forgets that 14 was already absorbed into 21's span; '3' for the last day stops at 30 instead of continuing past 31.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic