Problem overview
The method productExceptSelf receives an array of integers, nums, and returns an array of the same length. Entry i of the result is the product of every element of nums except nums[i]. The statement forbids division, and it asks for O(n) time and O(1) extra space, where the returned array doesn't count.
For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: the first entry is 2 * 3 * 4, the second is 1 * 3 * 4, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0]. Every product that includes the 0 is 0, and only the entry at the 0's own position leaves it out.
Approach: left products, then right products
The obvious plan multiplies everything and divides by nums[i]. It fails twice: division is banned, and a 0 in the array makes the division meaningless. The next idea, a nested loop that multiplies the other n - 1 elements for each position, works but costs O(n²).
The faster idea splits each answer in two. The product of everything except nums[i] is the product of everything to its left times the product of everything to its right. Both sides can be built with running products:
- The product to the left of
iis the product to the left ofi - 1timesnums[i - 1]. These are prefix products. - The product to the right of
iis built the same way, walking from the end.
Storing both sides in two extra arrays would work. The lesson saves memory instead: the first pass stores the left products directly in answer, and the second pass walks right to left with one running variable, suffix, and multiplies it into answer as it goes. Each right-side product is needed exactly once, so one variable is enough.
On [1, 2, 3, 4], the first pass leaves answer as [1, 1, 2, 6]. The second pass then goes like this:
i=3 answer=[1, 1, 2, 6] suffix=4
i=2 answer=[1, 1, 8, 6] suffix=12
i=1 answer=[1, 12, 8, 6] suffix=24
i=0 answer=[24, 12, 8, 6] suffix=24
Each line shows the state after the loop body for that i. The last entry changes first because nothing lies to its right, so its multiplier is the starting value of suffix, 1.
Step by step
- Store the length.
nums.countgoes into aletnamedn, because both loops need it. - Create
answer. It is avararray ofnzeros, andanswer[0]is set to 1. Nothing lies to the left of the first element, and a product of no numbers is 1, just as an empty sum is 0. - Loop from 1 up to
n - 1. Index 0 is already filled. - Extend the prefix product.
answer[i]becomesanswer[i - 1] * nums[i - 1]: the product up to the previous position, times the previous element. - Start
suffixat 1. It holds the product of everything to the right of the current index, and it must be avarbecause it changes on every step. - Walk from right to left with
stride(from: n - 1, through: 0, by: -1), which counts down and includes 0. - Multiply
answer[i]bysuffix. The entry held the left product, so it now holds left times right. - Then fold
nums[i]intosuffix. The order matters:answer[i]must not includenums[i]itself, so this line comes second. The next position to the left gets a suffix that coversnums[i]. - Return
answer.
The solution in Swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
let n = nums.count
var answer = [Int](repeating: 0, count: n)
answer[0] = 1
for i in 1..<n {
answer[i] = answer[i - 1] * nums[i - 1]
}
var suffix = 1
for i in stride(from: n - 1, through: 0, by: -1) {
answer[i] *= suffix
suffix *= nums[i]
}
return answer
}
}
Swift details worth knowing:
[Int](repeating: 0, count: n)builds an array ofncopies of 0. Sinceansweris avar, its elements can be assigned and updated with*=.1..<nis a half-open range. It covers 1 up ton - 1and is empty whennis 1. A range whose start is above its end, such as1..<0, stops the program with an error, which is one reason Swift code counts down withstrideinstead.stride(from:through:by:)includes the end value (through), whilestride(from:to:by:)excludes it. A negative step counts down.- Arrays are values.
answeris a local array that the method returns, so the caller receives its own copy andnumsis never changed. - Overflow traps.
Intis 64 bits, and in Swift an overflowing*stops the program rather than wrapping silently, even in an optimized build. The constraints promise that every product fits in 32 bits, so the lesson's tests never come near it. With larger values, such as twenty 30s, the same code crashes.
Complexity
Time: O(n). Each of the two loops visits every index once and does a constant amount of work per index.
Space: O(1) extra. Apart from the returned array, the method keeps only n, suffix and the loop variable.
Edge cases and common mistakes
- Zeros.
[0, 0, 2]gives[0, 0, 0]. With one zero, every entry except the zero's own position is 0, and with two or more, every entry is. The method needs no special case because it never divides. - Two elements.
[2, 3]gives[3, 2]: each answer is the other element. - Negative numbers.
[5, -5]gives[-5, 5]. Signs simply follow the multiplication. - Swapping the two suffix lines. If
suffix *= nums[i]runs beforeanswer[i] *= suffix, every entry also includes its own element. - Starting
answer[0]orsuffixat 0. Everything multiplies by 0, so the whole result is zeros. The starting value of a product is 1. - Empty input. The constraints promise at least two elements. With an empty array,
answer[0] = 1would be an index out of range, which stops the program.
Testing
[1, 2, 3, 4]gives[24, 12, 8, 6].[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0].[2, 3]gives[3, 2].[0, 0, 2]gives[0, 0, 0].[5, -5]gives[-5, 5].
