KatInterview

Modular Product Exclude Current Element

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashingarraysprefix-summath

Last updated

Compute the modular product of all elements in an array except the current element for each index without division.

Given an array of integers nums and an integer modulus mod, return an array result of equal length where each element result[i] is the product of all elements in nums except nums[i], evaluated modulo mod.

You must compute this without using division operations.

Constraints

  • 2 <= len(nums) <= 10^5
  • 1 <= nums[i] <= 10^9
  • 1 <= mod <= 10^9
  • Time Complexity: $\mathcal{O}(n)$, where $n$ is the length of nums.
  • Auxiliary Space Complexity: $\mathcal{O}(1)$ excluding the space required for the output array.

Examples

Example 1

Input: product_except_self([1, 2, 3, 4], 1000)

Output: [24, 12, 8, 6]

Example 2

Input: product_except_self([5, 2, 0], 100)

Output: [0, 0, 10]

Hints

Hint 1

Think about how to split the product at index i into two parts: elements to the left of i and elements to the right of i.

Hint 2

Can you compute the running product of elements from left to right, storing intermediate values in the result array?

Hint 3

How can you combine a second pass from right to left using a single running product variable?