DSA Tutorial



TIME & SPACE COMPLEXITY


ā±ļø Time and Space Complexity in DSA

Understanding how much time and space an algorithm needs helps us write efficient programs. Let's break down both.

šŸ“Œ What is Time Complexity?

Time complexity is the amount of time taken by an algorithm to run, as a function of the size of its input.

Example:
int sum = 0;
for (int i = 0; i < n; i++) {
    sum += i;
}
      

This loop runs n times ⇒ Time Complexity: O(n)

Common Time Complexities:

  • O(1): Constant time
  • O(n): Linear time
  • O(n²): Quadratic time
  • O(log n): Logarithmic time
  • O(n log n): Linearithmic time

šŸ’¾ What is Space Complexity?

Space complexity is the total memory space required by an algorithm, including input data, temporary variables, etc.

Example:
int arr[100];
      

This array takes space for 100 integers ⇒ Space Complexity: O(1) (as size is fixed)

Common Space Complexities:

  • O(1): Constant space
  • O(n): Linear space
  • O(n²): Space grows with square of input size

āœ… Tip: When designing an algorithm, always consider both time and space. Sometimes, we need to trade one for the other.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review