Solution in C# with comments


  • 0
    public class Solution {
        public int[] ProductExceptSelf(int[] nums) {
    
            // For storing backward products
            var a = new int[nums.Length];
            a[0] = nums[0];
            
            // For storing forward products
            var b = new int[nums.Length];
            b[nums.Length - 1] = nums[nums.Length - 1];
            
            // Calculate forward and backward products
            for(var i = 1; i < nums.Length; i++)
            {
                a[i] = a[i - 1] * nums[i];
                
                b[nums.Length - i - 1] = b[nums.Length - i] * nums[nums.Length - i - 1];
            }
            
            // Solve the question by multiplying backward product before i and forward product after i 
            for(var i = 1; i < nums.Length - 1; i++)
            {
                nums[i] = a[i - 1] * b[i + 1];
            }
            
            // Handle the two corner cases
            nums[0] = b[1];
            nums[nums.Length - 1] = a[nums.Length - 2];
            
            return nums;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.