Skip to content

visual walkthrough

Subarray Product Less Than K

MediumVariable Window (Counting)Reported at: AmazonMetaGoldman Sachs

Counting subarrays ending at each right index; a key counting trick.

Solve on LeetCode

The idea

All numbers are positive, so shrinking a window lowers its product and growing raises it. Keep the longest window ending at each position whose product is below k.

If a window of length L is valid, then all L subarrays ending at its right edge (starting anywhere inside) are valid too, so add L at each step.

Complexity

approachtimespace
Try every startO(n²)O(1)
Sliding windowO(n)O(1)

More walkthroughs