w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Calculate the space complexity and time complexity of a function

Space complexity: Identify data that occurs "in large quantities" or "repeatedly". Assign numbers to these quantities, e.g., N = number of lines in a file, or M = number of elements in an array. Add these quantities. Watch out for the dynamic creation of data structures: if you have an array of N numbers and another one of M numbers and you create a table of all the products, then the space complexity of the table is...

Time complexity: Identify repeated actions. Some may be hidden (as in Perl), some are explicit, e.g. in a for loop. Use the results of space complexity to quantify these repetititions. A loop may be terminated early: then you must estimate the average time of execution. Loops occurring one after the other add up. If you know that a loop body is executed N times and this body contains an inner loop that executes M times, then the body of that inner loop is executed - how often?

Very frequently it's just a simple exercise of counting, bookkeeping and simple arithmetic, although there are several examples where a good answer requires heavy math.

Not in your case!





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.