Lv.1arraymathprefix-sum
Product Except Self
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums, return an array whose i-th value is the product of every element except nums[i],
modulo . nums may contain 0.
Examples
| nums | result |
|---|---|
[1, 2, 3, 4] | [24, 12, 8, 6] |
[3, 0, 5] | [0, 15, 0] |
[1000000000, 1000000000] | [1000000000, 1000000000] |
Example 2 — only position 1 skips the 0, giving 3×5 = 15.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[]) → int[]
Constraints
-
nums.length -
nums[i] - Every returned value is taken modulo .
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| nums | Expected |
|---|---|
[1,2,3,4] | [24,12,8,6] |
[3,0,5] | [0,15,0] |
[1000000000,1000000000] | [1000000000,1000000000] |
Hint
Hint
The product without i is (product of everything left of i) × (product of everything right of i). Build both with one
pass each, taking the modulus after every multiplication (use 64-bit arithmetic). Dividing the total product by nums[i] fails
with zeros and does not work under a modulus. Multiplying the others for each position is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1356 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |