Find X Value of Array I - Problem

You are given an array of positive integers nums and a positive integer k. You are allowed to perform an operation once on nums, where in each operation you can remove any non-overlapping prefix and suffix from nums such that nums remains non-empty.

You need to find the x-value of nums, which is the number of ways to perform this operation so that the product of the remaining elements leaves a remainder of x when divided by k.

Return an array result of size k where result[x] is the x-value of nums for 0 <= x <= k - 1.

Note: A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it. A suffix of an array is a subarray that starts at any point within the array and extends to the end of the array. The prefix and suffix to be chosen for the operation can be empty.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,4], k = 5
Output: [0,1,2,1,2]
💡 Note: All possible subarrays: [2]→2%5=2, [2,3]→6%5=1, [2,3,4]→24%5=4, [3]→3%5=3, [3,4]→12%5=2, [4]→4%5=4. Count: remainder 0 appears 0 times, remainder 1 appears 1 time, remainder 2 appears 2 times, remainder 3 appears 1 time, remainder 4 appears 2 times.
Example 2 — Single Element
$ Input: nums = [7], k = 3
Output: [0,1,0]
💡 Note: Only one subarray [7]: 7 % 3 = 1. So remainder 1 appears once, others appear 0 times.
Example 3 — Multiple of k
$ Input: nums = [2,5], k = 10
Output: [1,0,1,0,0,1,0,0,0,0]
💡 Note: Subarrays: [2]→2%10=2, [2,5]→10%10=0, [5]→5%10=5. Count: remainder 0, 2, 5 each appear once.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 109
  • 2 ≤ k ≤ 105

Visualization

Tap to expand
Find X Value: Count Subarrays by Product Remainder234Input: nums = [2,3,4], k = 5[2] → 2%5 = 2[2,3] → 6%5 = 1[2,3,4] → 24%5 = 4[3] → 3%5 = 3[3,4] → 12%5 = 2[4] → 4%5 = 4Count by Remainder:01212Output: [0,1,2,1,2]
Understanding the Visualization
1
Input Array
Given array [2,3,4] and k=5
2
Generate All Subarrays
Find all contiguous subarrays and calculate product mod k
3
Count by Remainder
Group and count by remainder values 0 through k-1
Key Takeaway
🎯 Key Insight: Generate all contiguous subarrays and count occurrences of each product remainder
Asked in
Google 15 Amazon 12 Microsoft 8
18.5K Views
Medium Frequency
~25 min Avg. Time
567 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen