Product of integers

https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Large%20E-Commerce%20Company/E-Commerce%20Company%20-%20Interview%20Problems%20-%20SOLUTIONS/On-Site%20Question%202%20-%20SOLUTION.ipynb

On-Site Question 2 - SOLUTION

Problem

Given a list of integers, write a function that will return a list, in which for each index the element will be the product of all the integers except for the element at that index

For example, an input of [1,2,3,4] would return [24,12,8,6] by performing [2×3×4,1×3×4,1×2×4,1×2×3]

Requirements

You can not use division in your answer! Meaning you can‘t simply multiply all the numbers and then divide by eahc element for each index!

Try to do this on a white board or with paper/pencil.


Solution

If you look at the list above with the multiplication you‘ll notice we are repeating multiplications, such as 2 times 3 or 3 times 4 for multiple entries in the new list.

We‘ll want to take a greedy approach and keep track of these results for later re-use at other indices. We‘ll also need to think about what if a number is zero!

In order to find the products of all the integers (except for the integer at that index) we will actually go through our list twice in a greedy fashion.

On the first pass we will get the products of all the integers before each index, and then on the second pass we will go backwards to get the products of all the integers after each index.

Then we just need to multiply all the products before and after each index in order to get the final product answer!

Let‘s see this in action:

 
def index_prod(lst):

    # Create an empty output list
    output = [None] * len(lst)

    # Set initial product and index for greedy run forward
    product = 1
    i = 0

    while i < len(lst):

        # Set index as cumulative product
        output[i] = product

        # Cumulative product
        product *= lst[i]

        # Move forward
        i +=1

    # Now for our Greedy run Backwards
    product = 1

    # Start index at last (taking into account index 0)
    i = len(lst) - 1

    # Until the beginning of the list
    while i >=0:

        # Same operations as before, just backwards
        output[i] *= product
        product *= lst[i]
        i -= 1

    return output

In [20]:

index_prod([1,2,3,4])

Out[20]:

[24, 12, 8, 6]

In [21]:

index_prod([0,1,2,3,4])

Out[21]:

[24, 0, 0, 0, 0]

Review the solution and make sure you understand it! It uses O(n) time and O(n) space complexity!

Good Job!

时间: 2024-10-09 21:13:19

Product of integers的相关文章

Codeforces Round #447 (Div. 2) 题解 【ABCDE】

BC都被hack的人生,痛苦. 下面是题解的表演时间: A. QAQ "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of leng

codeforces 894B - Ralph And His Magic Field - [数学题]

题目链接:https://cn.vjudge.net/problem/CodeForces-894B Ralph has a magic field which is divided into n?×?m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't alway

Codeforces 894 B Ralph And His Magic Field

Discription Ralph has a magic field which is divided into n?×?m blocks. That is to say, there are n rows and m columns on the field. Ralph can put an integer in each block. However, the magic field doesn't always work properly. It works only if the p

Largest product from 3 integers

https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Ride%20Share%20Start-Up%20Company/Ride%20Share%20Company%20-%20Interview%20Questions%20-%20SOLUTIONS/On-Site%20Question%201%20-%20SOLUT

LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)

翻译 给定一个有n个数字的数组nums,其中n大于1,返回一个数组使得output[i]等于除nums[i]外所有元素的乘积. 不用分治并且在O(n)复杂度下解决这个问题. 例如,给定[1, 2, 3, 4],返回[24, 12, 8, 6]. 跟进: 你可以只在常量空间下完成它吗? (备注:在空间复杂度计算时输出数组不作为额外空间.) 原文 Given an array of n integers where n > 1, nums, return an array output such t

238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Fo

Maximum Pairwise Product

问题描述 Given a sequence of non-negative integers a0,…,an−1, find the maximum pairwise product, that is, the largest integer that can be obtained by multiplying two different elements from the sequence (or, more formally, max0≤i≠j≤n−1aiaj). Different el

【08_238】Product of Array Except Self

Product of Array Except Self Total Accepted: 26470 Total Submissions: 66930 Difficulty: Medium Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of numsexcept nums[i

HOJ 1096 Divided Product (DFS)

时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 Given two positive integers N and M, please divide N into several integers A1, A2, ..., Ak (k >= 1), so that: 1. 0 < A1 < A2 < ... < Ak; 2. A1 + A2 + ... + Ak = N; 3. A1, A2, ..., Ak are different with