Ruby O(n) time and O(1) space


  • 0
    K
    # @param {Integer[]} nums
    # @return {Integer[]}
    def product_except_self(nums)
        ans = [1]
        # Calculate the left side values
        (1..(nums.length - 1)).each do |i|
           ans[i] = ans[i-1] * nums[i-1] 
        end
        
        r = 1
       # Calculate right side values
        ((nums.length-1).downto(0)).each do |i|
            ans[i] *= r
            r *= nums[i]
        end
        ans
    end
    

Log in to reply
 

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