Back to course home
0% completed
Vote For New Content
Linear Space: O(n)
Linear Space Complexity O(n) refers to algorithms where the memory usage grows linearly with the input size. This occurs when an algorithm needs to store a new copy of the input or requires auxiliary data structures proportional to the input size.
Key Characteristics
In an algorithm with O(n) space complexity:
- The memory usage increases linearly with the size of the input.
- Common in tasks that duplicate the input data or process each element with additional storage.
Code Example 1: Copying a String
Let’s look at an example where we create a copy of a string. This requires memory proportional to the length of the string, resulting in O(n) space complexity.
Python3
Python3
. . . .
- Explanation:
- The
copy_string
method takes an input strings
and creates a copycopied_str
. - Since
copied_str
is a complete duplicate ofs
, it requires memory proportional to the length ofs
, resulting in O(n) space complexity.
- The
Code Example 2: Copying an Array
Here’s another example that demonstrates O(n) space complexity by creating a copy of an array.
Python3
Python3
. . . .
- Explanation:
- This
copy_array
function takes an input arrayarr
and creates a duplicatecopied_arr
. - Since
copied_arr
contains each element ofarr
, it requires memory proportional to the size ofarr
, resulting in O(n) space complexity.
- This
.....
.....
.....
Like the course? Get enrolled and start learning!
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible