Search code examples
pythonpython-3.xbig-ocombinations

Time complexity of a combination function


I have this function that creates pairs from a list of numbers. We know that there will be a total of n choose 2 iterations every time. So does that make the time complexity O(nC2)? or is it O(n^2)?

If it is O(n^2) why is it O(n^2)? The function does not iterate that many times and it never will.

def find_pairs(nums):
    pairs = []
    for i in range(len(nums)):
        current = nums[i]

        for n in nums[i+1:]:
            pairs.append((current, n))

    return pairs

Solution

  • Time complexity isn't about exactly how many times an algorithm is run, it's how the algorithm scales.

    In your case n choose 2 is equal to:

    n! / (2 * (n - 2)!)
    

    This can be simplified to

    n * (n-1) / 2 = (n^2 - n) / 2
    

    As you can see we have a 2nd degree polynomial function (quadratic). Therefore we consider the time complexity to be O(n^2) since it will scale quadratically.