Search code examples
time-complexitypseudocodemathematical-optimization

How to calculate time and space complexity from a pseudocode?


I am asked to determine use the time and space complexities of simple algorithms. The problem is that I don't fully understand where the numbers come from. From example we were provided it counts addition, subtraction, division, and multiplication as primitive operations.

Here I am posting pseudo code of my algorithm which calculates standard deviation by using formula we were provided.

I see 2 * (n - 1) addition symbols, 1 division symbol, 2 multiplication symbol and 1 subtraction symbol.

What else I must count here for time complexity? And what to do with space complexity?

// X is passed array, and N is number of elements in array.
Algorithm calculateStandardDeviation(X, N)
{
    private double arraySum;
    private double arrayMean;
    private double xi2;
    private double standardDeviation;

    foreach (arrayValue in X)
    {
        arraySum = arraySum + arrayValue;
    }

    arrayMean = sum / N;

    foreach (arrayValue in X)
    {
        xi2 = xi2 + Math.Pow(arrayValue, 2);
    }

    standardDeviation = Math. Sqrt(((1/N) * () * xi2) - Math.Pow(arrayMean, 2));

    return standardDeviation;
}

Solution

  • Algorithmic Complexity can, ironically, be as general or complex as you want. If you are working towards a big-oh O(...) notation complexity - as is the norm in computer science - @david robinson is correct with respect to your current situation.

    A for loop generally adds a dimension of N time complexity - where N is the number of runs your loop contains. Everything else you do runs in O(1) "constant" time (does NOT mean takes the same amount of physical time as another O(1) time op). Therefore, your time complexity is the linear addition of all your operations or O(N + N + 1 + 1+...) = O(2N). This, i'm sure you learned in class, reduces to O(N). Time complexity.

    Now for space complexity - same thing. Does anything grow as your input sizes grow? That would be a yes - your array grows as you add more elements to your array. Therefore it, too, grows as O(N). You have other constant space factors, but we're dropping that for big-oh, giving you

    linear - O(N) - in time and space complexity.