Space & Time Complexity Visualization

·

2 min read

Space Complexity
Imagine you have a bookshelf that represents the memory used by your program. Each book on the shelf represents a variable in your program.

Suppose there are only three variables: y, x, and i. So, there are only three books on the shelf, regardless of how many times the loops in the program run. Even as y and x take on different values in each iteration of the loop, you’re not adding more books to the shelf; you’re just changing the contents of the existing books.

This is why we say the space complexity is O(1), or constant. No matter how big the input gets (in this case, the range of values that y and x can take), the number of books on the shelf doesn’t change. The amount of memory used by the program remains constant.

Time Complexity
Imagine you’re a librarian and you have a bookshelf with n books. Each book represents a task you need to complete.

  • If you have to check each book once, this would be like a single loop in a program. You go through each book from the first to the last, checking them one by one. This would take you n units of time, so we say this has a time complexity of O(n).

  • Now, imagine that for each book, you also need to compare it with every other book on the shelf. This would be like a nested loop in a program. For each book, you spend n units of time comparing it with the others, and since there are n books, the total time is n * n, or n^2. This is O(n^2) time complexity.

Did you find this article valuable?

Support SAHIL ALI by becoming a sponsor. Any amount is appreciated!