Space Complexity of Algorithms
Space Complexity of Algorithms
Space complexity is the total amount of memory space used by an algorithm/program including the
space of input values for execution. So to find space complexity, it is enough to calculate the space
occupied by the variables used in an algorithm/program.
Example #1
Explanation: Do not misunderstand space complexity to be 1364 Kilobytes as shown in the output
image. The method to calculate the actual space complexity is shown below.
In the above program, 3 integer variables are used. The size of the integer data type is 2 or 4 bytes
which depends on the compiler. Now, lets assume the size as 4 bytes. So, the total space occupied
by the above-given program is 4 * 3 = 12 bytes. Since no additional variables are used, no extra
space is required.
Example #2
Join Our Telegram Group to Get Notifications, Study Materials, Practice test & quiz:
https://t.me/ccatpreparations Visit: https://ccatpreparation.com
Explanation:
In the above-given code, the array consists of n integer elements. So, the space occupied by the array is 4 * n.
Also we have integer variables such as n, i and sum. Assuming 4 bytes for each variable, the total space
occupied by the program is 4n + 12 bytes. Since the highest order of n in the equation 4n + 12 is n, so the
space complexity is O(n) or linear.
Summary
Constant Space Complexity occurs when the program doesn’t contain any loops, recursive
O(1) functions or call to any other functions.
Linear space complexity occurs when the program contains any loops.
O(n)
Join Our Telegram Group to Get Notifications, Study Materials, Practice test & quiz:
https://t.me/ccatpreparations Visit: https://ccatpreparation.com