C# solution: constant space


  • 0
    B
    public class Solution 
    {
        public int[] ProductExceptSelf(int[] nums) 
        {
            int n = nums.Length;
            if (n == 0) return nums;
            
            var result = new int[n];
            result[0] = 1;
            for (int i = 1; i < n; i++)
            {
                result[i] = nums[i - 1] * result[i-1]; 
            }
            
            int right = nums[n - 1];
            
            for (int i = n - 2; i >= 0; i--)
            {
                result[i] = result[i] * right;
                right = right * nums[i];
            }
            
            return result;
        }
    }
    

Log in to reply
 

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