Taro Logo

Subarray Product Less Than K

#142 Most AskedMedium
0 views
Topics:
ArraysTwo PointersSliding Windows

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

Example 1:

Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Example 2:

Input: nums = [1,2,3], k = 0
Output: 0

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 1 <= nums[i] <= 1000
  • 0 <= k <= 106

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the array contain negative numbers or zeros, or are all elements strictly positive integers?
  2. What should be returned if $k$ is less than or equal to 1, or if the array is empty?
  3. Can the product of the elements exceed the maximum limit of standard integer types, and should I worry about integer overflow?
  4. Are the contiguous subarrays considered distinct based on their values, or strictly by their start and end indices in the original array?
  5. Is the return value guaranteed to fit within a standard 32-bit integer, or could the total count exceed standard limits requiring a 64-bit integer?

Brute Force Solution

Approach

Imagine you have a line of numbered blocks and you want to find every possible contiguous group of blocks whose multiplied value is strictly less than a given target number. The brute force approach exhaustively checks every single possible group one by one to see if it meets the condition.

Here's how the algorithm would work step-by-step:

  1. Start by looking at every possible single block on its own, multiply its value, and check if that total is smaller than your target number.
  2. If it is, count it as a valid group.
  3. Next, look at every possible group of two adjacent blocks, multiply their values together, and check if that product is smaller than the target.
  4. If it is, count that group as well.
  5. Continue this process by looking at groups of three adjacent blocks, then four, and so on, until you have tested every possible continuous stretch of blocks from start to finish.
  6. Keep a running total of every single group you test whose product falls below the target limit.
  7. Once you have checked every conceivable starting point and ending point combination, your running total gives you the final answer.

Code Implementation

def numSubarrayProductLessThanK(nums, target_limit):    # If the target limit is 1 or less, no positive number product can be strictly less than it    if target_limit <= 1:        return 0    valid_group_count = 0    # Iterate through every possible starting position for our contiguous groups of blocks    for start_index in range(len(nums)):        current_product = 1        # Expand the group one block at a time to evaluate every possible ending position        for end_index in range(start_index, len(nums)):            current_product *= nums[end_index]            # Stop checking larger groups once the product meets or exceeds the target limit            if current_product >= target_limit:                break            valid_group_count += 1    return valid_group_count

Big(O) Analysis

Time Complexity
O(n²) – The brute-force strategy uses nested loops where the outer loop selects every possible starting point among the n blocks, and the inner loop extends the group to every possible ending point. For the first block we check up to n groups, for the second block (n-1) groups, and so on until the final block. Summing these checks yields approximately n * (n + 1) / 2 total operations, which simplifies in Big O notation to O(n²).
Space Complexity
O(1) – The algorithm relies strictly on a few primitive scalar variables, such as pointers for the start and end of the current contiguous block, a running product total, and a counter for valid groups. Because no auxiliary data structures like temporary lists, hash maps, or recursion stacks are utilized, the extra memory required remains entirely constant regardless of the input size N. Therefore, the auxiliary space complexity is O(1).

Optimal Solution

Approach

Instead of checking every single combination of numbers, the optimal strategy uses a clever shrinking and expanding window to keep track of valid groups. By sliding this window forward efficiently, we can count all qualifying groups without wasting time recalculating products from scratch.

Here's how the algorithm would work step-by-step:

  1. Imagine a flexible window that starts small at the very beginning of your sequence of numbers.
  2. Gradually expand the window to the right by including the next number, and multiply this new number into the running total product.
  3. If the running product ever becomes equal to or greater than the target limit, shrink the window from the left by removing numbers until the product drops back below the target limit.
  4. Every time the window size changes or a new number is successfully included, count all the possible valid sub-groups that can be formed using the numbers currently inside the window.
  5. Slide the right side of the window forward again to test the next number, repeating the expansion and shrinking process until you reach the end of the sequence.
  6. Sum up all the counts gathered along the way to get your final answer without ever needing to check every possible combination manually.

Code Implementation

def num_subarray_product_less_than_k(number_sequence, target_limit):
    if target_limit <= 1:
        return 0

    total_valid_subarrays = 0
    current_product = 1
    left_window_pointer = 0

    # Expand the right boundary to incorporate new elements into the sliding window product.
    for right_window_pointer in range(len(number_sequence)):
        current_product *= number_sequence[right_window_pointer]

        # Shrink the left boundary when the product violates the limit condition.
        while current_product >= target_limit:
            current_product //= number_sequence[left_window_pointer]
            left_window_pointer += 1

        # Accumulate all valid subarrays ending at the right pointer and starting within the window.
        total_valid_subarrays += right_window_pointer - left_window_pointer + 1

    return total_valid_subarrays

Big(O) Analysis

Time Complexity
O(n) – Although the strategy uses two pointers representing a sliding window over an array of size n, neither pointer ever moves backward. The right pointer iterates through all n elements to expand the window, while the left pointer only moves forward to shrink the window when the product limit is exceeded. Therefore, each element is visited at most once by the left pointer and once by the right pointer, resulting in roughly 2n total operations that simplify to O(n).
Space Complexity
O(1) – The algorithm relies entirely on a fixed set of primitive variables such as the left and right pointers, the running product, and the total count accumulator. No auxiliary data structures, temporary lists, or recursion stack frames scaling with the input size $N$ are required. Because memory consumption remains constant regardless of how many numbers are in the input sequence, the auxiliary space complexity is strictly $O(1)$.

Edge Cases

Empty or null input array
How to Handle:
Return zero immediately since no valid subarrays can exist.
K is zero or negative
How to Handle:
Return zero immediately because no product of positive integers can be strictly less than a non-positive number.
Array containing zeros
How to Handle:
The sliding window naturally handles zeros by making products zero, which are strictly less than positive k.
Array containing negative numbers
How to Handle:
Standard sliding window fails with negatives because multiplying by a negative reverses monotonicity, requiring alternative approaches.
All elements are 1 and k is large
How to Handle:
The window expands to maximum size and the formula right minus left plus one correctly counts all combinations.
Extremely large numbers causing integer overflow
How to Handle:
Use 64-bit integers for the running product to prevent arithmetic overflow during continuous multiplication.
Single element array
How to Handle:
Return one if that element is less than k, otherwise return zero.
No subarrays have a product less than k
How to Handle:
The counter remains at zero and the function correctly returns zero.
0/257 completed