Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I reduce time complexity on this algorithm?

I have this exercise and the goal is to solve it with complexity less than O(n^2).

You have an array with length N filled with event probabilities. Create another array in which for each element i calculate the probability of all event to happen until the position i.

I have coded this O(n^2) solution. Any ideas how to improve it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

probabilityTable = [0.1, 0.54, 0.34, 0.11, 0.55, 0.75, 0.01, 0.06, 0.96]

finalTable = list()

for i in range(len(probabilityTable)):
    finalTable.append(1)
    for j in range(i):
        finalTable[i] *= probabilityTable[j]

for item in finalTable:
    print(item)

>Solution :

probabilityTable = [0.1, 0.54, 0.34, 0.11, 0.55, 0.75, 0.01, 0.06, 0.96]

finalTable = probabilityTable.copy()

for i in range(1, len(probabilityTable)):
    finalTable[i] = finalTable[i] * finalTable[i - 1]

for item in finalTable:
    print(item)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading