Time Complexity and Space Complexity

Time Complexity

“In computer science, the time complexity is the computational complexity that describes the amount of time it takes to run an algorithm.”

The time complexity is the runtime of the code, and it is expressed by big O notation. Big O notation means we only look at the highest exponent of the runtime, without considering its coefficients or other lower order terms.

For example, if the precise function of the time complexity of the code is:

We would said it is O(n²), we do not consider its coefficient 5 and other lower terms such as 3n and log2(n).

When determine runtime of the code we should not memorize which big-O expression goes with a given algorithmic structure, we should count up the number of operations that the algorithm requires and compare that to the size of the input.

Space Complexity

The space complexity of an algorithm or a computer program is the amount of memory space required to solve an instance of the computational problem as a function of characteristics of the input. It is the memory required by an algorithm to execute a program and produce output.

Similar to time complexity, space complexity is often expressed asymptotically in big O notation, such as O(n),O(n log n), O(n^α),O(2^n), etc., where n is a characteristic of the input influencing space complexity.

Storing values in variables always take memory (RAM), examples:

Most Primitives like numbers and booleans take O(1)/Constant Space

Strings, Arrays, and Objects take up O(n)/ Linear Space

Time Complexity Prioritized Over Space Complexity

The cost to produce and run processors are much higher compare to RAM. The speed is more important to users compare to RAM usage.