Search code examples
pythonbig-ocode-complexity

How to find complexity for the following program?


So I am not a CS major and have hard time answering questions about a program's big(O) complexity.

I wrote the following routine to output the pairs of numbers in an array which sum to 0:

asd=[-3,-2,-3,2,3,2,4,5,8,-8,9,10,-4]

def sum_zero(asd):
    for i in range(len(asd)):
        for j in range(i,len(asd)):
            if asd[i]+asd[j]==0:
                print asd[i],asd[j]

Now if someone asks the complexity of this method I know since the first loop goes thorough all the n items it will be more than (unless I am wrong) but can someone explain how to find the correct complexity?

If there is better more efficient way of solving this?


Solution

  • I won't give you a full solution, but will try to guide you.

    You should get a pencil and a paper, and ask yourself:

    How many times does the statement print asd[i], asd[j] execute? (in worst case, meaning that you shouldn't really care about the condition there)
    You'll find that it really depends on the loop above it, which gets executed len(asd) (denote it by n) times.

    The only thing you need to know, how many times is the inner loop executed giving that the outer loop has n iterations? (i runs from 0 up to n)

    If you still not sure about the result, just take a real example, say n=20, and calculate how many times is the lowest statement executed, this will give you a very good indication about the answer.