Beats 100% of Ruby solutions


  • 0
    P
    # get product of nums before each index and place in array
    # get product of nums after each index and place in array
    # multiply the two values from each array together
    def product_except_self(nums)
    	
    	# multiplication of all integers before each index, start from beginning index (0) to last index (3)
    	product_of_nums_before_index = [] 
    	i = 0 
    	finish = nums.length - 1
    	product_so_far  = 1
    	while i <= finish
    		product_of_nums_before_index[i] = product_so_far
    		product_so_far = product_so_far * nums[i]
    		i +=1
    	end
    
    	#  multiplication of all integers  after each index
    	product_of_nums_after_index = []	
    	product_so_far  = 1
    	i = nums.length - 1 # start from last element work to left
    	finish = 0
    	product_so_far  = 1
    	while i >= finish
    		product_of_nums_after_index[i] = product_so_far
    		product_so_far = product_so_far * nums[i]
    		i -= 1
    	end 
    	
    	# multiply the products from the two arrays together and push into result
    	result = []
    	product = 1
    	(0..(nums.length - 1)).each do |i|
    		result << product_of_nums_before_index[i] * product_of_nums_after_index[i]
    	end 
    
    	return result
    
    end
    

Log in to reply
 

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