FastPrepCount Subarrays With Product Equal to K
Problems/Count Subarrays With Product Equal to K

Count Subarrays With Product Equal to K

Salesforce logoSalesforce● MediumFULLTIMEOA
QuestionFunctionExamplesConstraints

Problem statement

Source note: In a Salesforce online assessment, one of the two questions was a well-known count of subarrays with a small product, changed so that the product must equal k instead of staying below it. The candidate said a brute-force check did not pass every test, and a two-pointer pass did.

The report gives no value range, limits or examples. Here, every value and k are positive integers, and the limits and examples are ours.

The judged task matches the report at about 85%.

You are given an array of positive integers nums and a positive integer k.

A subarray is a contiguous, non-empty part of nums. Return the number of subarrays whose product of all elements is exactly k.

Subarrays that cover different index ranges are counted separately, even when they hold the same values.

Function

countProductSubarrays(nums: int[], k: int) → int

Examples

Example 1

nums = [2,3,1,6,1]k = 6return = 6

The subarrays whose product is exactly 6 are:

  • [2,3] and [2,3,1], since 2 * 3 = 6 and multiplying by 1 changes nothing.
  • [6], [1,6], [6,1] and [1,6,1].

Any other subarray multiplies to something else, for example [3,1,6] gives 18. The answer is 6.

Example 2

nums = [1,1,1]k = 1return = 6

Every product is 1, so all 6 subarrays count: three of length 1, two of length 2 and one of length 3.

Example 3

nums = [4,5,10]k = 3return = 0

Every value is larger than 3, so every product is larger than 3. The answer is 0.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • 1 <= nums[i] <= 1000
  • 1 <= k <= 10^6

More Salesforce problems

  • Minimum No-Repeat Segments After One Character RemovalOA · Seen Nov 2026
  • Get Message StatusOA · Seen Nov 2026
  • Detect a Cycle in a Linked ListPHONE SCREEN · Seen Oct 2026
All Salesforce interview questionsSee Salesforce hiring insights
Saved
public int countProductSubarrays(int[] nums, int k) {
    // Write your code here.
}
Checking account…