LeetCode Blind 75 in Swift: Solving the "Product of Array Except Self" Problem

Problem: Product of Array Except Self

The Product of Array Except Self problem asks you to return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
        

Swift Solution

class Solution {
    func productExceptSelf(_ nums: [Int]) -> [Int] {
        let n = nums.count
        var answer = Array(repeating: 1, count: n)

        var leftProduct = 1
        for i in 0..

        

Explanation

In this solution, we first calculate the product of all elements to the left of each element and store it in the answer array. Then, we calculate the product of all elements to the right of each element and multiply it with the corresponding value in the answer array. This approach avoids division and runs in O(n) time.

Comments

Popular posts from this blog

LeetCode Blind 75 in Swift: Solving the "Find Minimum in Rotated Sorted Array" Problem

LeetCode Blind 75 in Swift: Solving the "3Sum" Problem