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!

Product of integers的更多相关文章

  1. hdu 6125 -- Free from square(状态压缩+分组背包)

    题目链接 Problem Description There is a set including all positive integers that are not more then n. Ha ...

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

    BC都被hack的人生,痛苦. 下面是题解的表演时间: A. QAQ "QAQ" is a word to denote an expression of crying. Imag ...

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

    题目链接:https://cn.vjudge.net/problem/CodeForces-894B Ralph has a magic field which is divided into n × ...

  4. Codeforces 894.B Ralph And His Magic Field

    B. Ralph And His Magic Field time limit per test 1 second memory limit per test 256 megabytes input ...

  5. Codeforces Round #447 (Div. 2) B. Ralph And His Magic Field【数论/组合数学】

    B. Ralph And His Magic Field time limit per test 1 second memory limit per test 256 megabytes input ...

  6. HDU 6125 Free from square 状态压缩DP + 分组背包

    Free from square Problem Description There is a set including all positive integers that are not mor ...

  7. Codeforces Round #232 (Div. 2) C

    C. On Number of Decompositions into Multipliers time limit per test 1 second memory limit per test 2 ...

  8. Codeforces G. Nick and Array(贪心)

    题目描述: Nick had received an awesome array of integers a=[a1,a2,…,an] as a gift for his 5 birthday fro ...

  9. Codeforces Round #569 (Div. 2) B. Nick and Array

    链接: https://codeforces.com/contest/1180/problem/B 题意: Nick had received an awesome array of integers ...

随机推荐

  1. eclipse运行程序时报java.lang.OutOfMemoryError: Java heap space内存不足问题

    System.setProperty("webdriver.firefox.bin", "D:\\Mozilla Firefox\\firefox.exe"); ...

  2. linux 下常用部分命令

    关机 (系统的关机.重启以及登出 ) shutdown -h now 关闭系统() init 关闭系统() shutdown -h hours:minutes & 按预定时间关闭系统 shut ...

  3. FireDAC FDQuery

    http://docwiki.embarcadero.com/RADStudio/XE6/en/TFDMemTable_Questions#Q:_How_can_I_copy_all_records_ ...

  4. 迭代器iter()

    from collections import Iterable print(isinstance({},iterable)) # 判断是否可迭代 from collections import It ...

  5. Mysql 主键常用修改

    修改表的定增长初始值: ALTER TABLE 表名 AUTO_INCREMENT=值;

  6. C#连接sqlserver windows 和 sqlserver 身份验证的两种连接字符串

    //sql server 身份验证 连接字符串 private string ConnstrSqlServer = "server=服务器名称;uid=登录名称;pwd=登录密码;datab ...

  7. autolayout UILabel 设置最大宽度

    label1.preferredMaxLayoutWidth = 100: label1.numberOfLines = 0; //自适应行数

  8. 千万级高并发负载均衡软件haproxy配置文件详解

    balance roundrobin         #轮询方式 balance source               #将用户IP经过hash计算后,使同一IP地址的所有请求都发送到同一固定的后 ...

  9. 趣味编程:静夜思(JOOL版)

    JOOL <dependency> <groupId>org.jooq</groupId> <artifactId>jool</artifactI ...

  10. MapReduce超时原因(Time out after 300 secs)

    目前碰到过三种原因导致 Time out after 300 secs. 1. 死循环 这是最常见的原因.显式的死循环很容易定位,隐式的死循环就比较麻烦了,比如正则表达式.曾经用一个网上抄来的邮箱正则 ...