LeetCode #3524 — MEDIUM

Find X Value of Array I

Move from brute-force thinking to an efficient approach using array strategy.

Solve on LeetCode
The Problem

Problem Statement

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.

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.

Note that the prefix and suffix to be chosen for the operation can be empty.

Example 1:

Input: nums = [1,2,3,4,5], k = 3

Output: [9,2,4]

Explanation:

  • For x = 0, the possible operations include all possible ways to remove non-overlapping prefix/suffix that do not remove nums[2] == 3.
  • For x = 1, the possible operations are:
    • Remove the empty prefix and the suffix [2, 3, 4, 5]. nums becomes [1].
    • Remove the prefix [1, 2, 3] and the suffix [5]. nums becomes [4].
  • For x = 2, the possible operations are:
    • Remove the empty prefix and the suffix [3, 4, 5]. nums becomes [1, 2].
    • Remove the prefix [1] and the suffix [3, 4, 5]. nums becomes [2].
    • Remove the prefix [1, 2, 3] and the empty suffix. nums becomes [4, 5].
    • Remove the prefix [1, 2, 3, 4] and the empty suffix. nums becomes [5].

Example 2:

Input: nums = [1,2,4,8,16,32], k = 4

Output: [18,1,2,0]

Explanation:

  • For x = 0, the only operations that do not result in x = 0 are:
    • Remove the empty prefix and the suffix [4, 8, 16, 32]. nums becomes [1, 2].
    • Remove the empty prefix and the suffix [2, 4, 8, 16, 32]. nums becomes [1].
    • Remove the prefix [1] and the suffix [4, 8, 16, 32]. nums becomes [2].
  • For x = 1, the only possible operation is:
    • Remove the empty prefix and the suffix [2, 4, 8, 16, 32]. nums becomes [1].
  • For x = 2, the possible operations are:
    • Remove the empty prefix and the suffix [4, 8, 16, 32]. nums becomes [1, 2].
    • Remove the prefix [1] and the suffix [4, 8, 16, 32]. nums becomes [2].
  • For x = 3, there is no possible way to perform the operation.

Example 3:

Input: nums = [1,1,2,1,1], k = 2

Output: [9,6]

Constraints:

  • 1 <= nums[i] <= 109
  • 1 <= nums.length <= 105
  • 1 <= k <= 5
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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. 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. Note that the prefix and suffix to be chosen for the operation can be empty.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Dynamic Programming

Example 1

[1,2,3,4,5]
3

Example 2

[1,2,4,8,16,32]
4

Example 3

[1,1,2,1,1]
2
Step 02

Core Insight

What unlocks the optimal approach

  • Use dynamic programming.
  • Define <code>dp[i][r]</code> as the count of subarrays ending at index <code>i</code> whose product modulo <code>k</code> equals <code>r</code>.
  • Compute <code>dp[i][r]</code> for each index <code>i</code> in <code>nums</code> and sum over all indices to get the final counts for each remainder.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3524: Find X Value of Array I
class Solution {
  public long[] resultArray(int[] nums, int k) {
    long[] ans = new long[k];
    // dp[r] := the number of subarrays ending at current position with
    // product % k == r
    long[] dp = new long[k];

    for (final int num : nums) {
      long[] newDp = new long[k];
      final int numMod = num % k;
      // Start new subarray with only `num`.
      newDp[numMod] = 1;
      // Extend all previous subarrays.
      for (int i = 0; i < k; ++i) {
        final int newMod = (int) (1L * i * numMod % k);
        newDp[newMod] += dp[i];
      }
      // Accumulate counts into ans.
      for (int i = 0; i < k; ++i)
        ans[i] += newDp[i];
      dp = newDp;
    }

    return ans;
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.