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

  • 0
    [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)
    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.
    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];
              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.