C# solution 2 pass without extra space with explanation. Can we optimize more?


  • 0
    D
    /*
    input:
    [2 2 3 4]
    
    1st pass from beginning:
    Intermediate output: Calculate in each index i the product until 
    previous index i-1 (1 for 1st element)
    [1,2,4,12]
    
    2nd pass from end:
    Output: Now that  intermedidate output[i] contains product until previous 
    element we do the same from end and additionally just multiply with itself. in case of 0's it will autocorrect itself 
    without special conditions.
    
    Output:
    [24,24,16,12]
    */
    public class Solution {
        public int[] ProductExceptSelf(int[] nums) {
            int previoustotal = 1;
            int[] output = new int[nums.Length];
            for(int i = 0 ; i < nums.Length; i++){
              output[i] = previoustotal;
              previoustotal *= nums[i];
             }
              previoustotal=1;
              for(int i = nums.Length-1 ; i >=0; i--){
                output[i] = output[i]*previoustotal;
                previoustotal *=nums[i];
              }
              return output;
            }
    }
    

Log in to reply
 

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