Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Sliding window

Count runs whose product is below k

Medium · Target 20 minutes · Sliding window· Type asked at

Given an array nums of positive integers and an integer k, return the number of contiguous subarrays whose product is strictly less than k.

Examples

InputOutputWhy
nums = [10,5,2,6], k = 1008[10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6].
nums = [1,2,3], k = 00No product of positive numbers is below 0.
nums = [1,1,1], k = 26Every subarray has product 1.

Constraints

  • 1 ≤ n ≤ 3 × 10⁴
  • 1 ≤ nums[i] ≤ 1000
  • 0 ≤ k ≤ 10⁶

Hints

Hint 1

All numbers are at least 1, so extending a subarray never lowers its product.

Hint 2

For each right end hi, find the furthest-left start lo with product below k. How many valid subarrays end at hi?

Hint 3

Exactly hi − lo + 1: every start from lo to hi. Add that at each step.

Where people lose marks

  • Forgetting k ≤ 1: the window can never be valid, and the shrink loop must not run past hi.
  • Overflow when the product is kept without shrinking: in this method it never exceeds k × 1000, which fits in 64 bits.
  • Adding 1 per valid window instead of hi − lo + 1.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.