C# - O(n) no extra space - forward then backwards - 2 pass


  • 0
        public int[] ProductExceptSelf(int[] nums) 
        {
            int[] arr = new int[nums.Length];
            
            // forward
            int prod = 1;
            for (int i = 0; i < nums.Length; i++)
            {
                prod *= nums[i];
                arr[i] = prod;
            }
            
            // backwards
            prod = 1;
            for (int i = nums.Length - 1; i >= 0; i--)
            {
                arr[i] = prod * (i > 0 ? arr[i-1] : 1);
                prod *= nums[i];
            }
            
            return arr;
        }
    

Log in to reply
 

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