Example 1
- Input
- nums = [1, 2, 3, 4]
- Output
- [24, 12, 8, 6]
Skip each position: 2 * 3 * 4 = 24, 1 * 3 * 4 = 12, 1 * 2 * 4 = 8, and 1 * 2 * 3 = 6.
For each position, multiply every number except the one at that position. Return those products in order, without division, in linear time.
Given an integer array nums, build an array answer of the same length. For each index i, answer[i] must multiply all values in nums except nums[i]. Exclude a position, not every occurrence of its value.
The solution must take time without division, where n is the array length. Products of all prefixes (sections starting at the first element) and suffixes (sections ending at the last element) fit in a signed 32-bit integer.
Follow-up: use extra space. The returned answer array does not count as extra space; any other arrays do.
2 <= nums.length <= 100000-30 <= nums[i] <= 30answer[i], prefix product, and suffix product fits in a signed 32-bit integer.Skip each position: 2 * 3 * 4 = 24, 1 * 3 * 4 = 12, 1 * 2 * 4 = 8, and 1 * 2 * 3 = 6.
At the smallest allowed length, each answer is simply the other number.
Only index 2 skips the zero: (-1) * 1 * (-3) * 3 = 9; every other product contains zero.
Skipping one position still leaves at least one zero in every product.
Split the array at the position you must skip: everything to its left and everything to its right. Their products combine into the answer. For index 2 in [1, 2, 3, 4], the left product is 1 * 2 = 2, the right product is 4, and the answer is 2 * 4 = 8. A side with no elements contributes 1, because multiplying by 1 leaves the other side unchanged. Two sweeps reuse these products instead of starting over for each position.
Reveal Brute Force: intuition, complexity, and code
[2, 5] returns [5, 2]. Empty and single-element arrays are outside this problem's constraints.[2, 2, 2] returns [4, 4, 4]. Skip one position, not every matching value.[1, 1, 1] returns [1, 1, 1]; starting products at 1 also handles an empty side.[-1, 1, 0, -3, 3] returns [0, 0, 9, 0, 0]. Only the zero's position can have a nonzero answer.[0, 2, 0, 4] returns all zeros. Even a long run of large values between two zeros must return zeros, never NaN.[-1, 2, -3, 4] returns [-24, 12, -8, 6]; ordinary multiplication preserves the correct signs.1, and the operation is multiplication.In the Arrays & Hashing pattern, two directional sweeps can combine information from both sides of an index. Save one side in the output and carry the other in a running value to avoid repeated work and extra arrays.