6

I'm a bit lost on Auxiliary Space Complexities.

In the lecture that I am taking the instructor states that strings have a space complexity O(n), since the length of the string(n) will vary. But primitives such as numbers, booleans, undefined, etc have a constant space complexity O(1).

I'm confused because if the space of strings differ by its length, would that not be the same with numbers as well? Since they also will have different "lengths"?

I do understand how booleans and undefined is O(1), I mean true/false, undefined and null are length-independent instances.

If anyone can clarify this for me, I would appreciate it.

funnydman
  • 9,083
  • 4
  • 40
  • 55
ninja_nugget
  • 712
  • 1
  • 8
  • 19
  • 1
    If you do have to deal with arbitrarily large numbers, then storing the integer N would take O(log |N|) bits of space, and then you also have to consider the time complexity of doing arithmetic operations on them (since you can't add/subtract/multiply/divide arbitrarily large numbers in O(1) time). For simplicity, it's normally assumed that the numbers involved aren't "too large" in magnitude compared to the problem's actual input size, but you do have to be more careful when the input is just a single number. – kaya3 Feb 11 '20 at 12:18
  • 1
    A string is basically an array of characters (or bytes), and an array has size O(n) where `n` is the number of elements. – ChatterOne Feb 11 '20 at 13:19

2 Answers2

4

In real world number size is indeed unlimited, however here it's about numerical primitives. Each primitive by definition requires a fixed number of storage units (and that's the reason why it can hold only a limited range of values). Unlike numerical primitives, size of a string is theoretically unlimited and it occupies storage corresponding to input size (i.e., characters which constitute the string).

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
1

All numbers used by computers are limits. For example, C's limits are here. So if you attempt to assign number outside this limit, the program either errors or starts behaving weird. This then means that numbers can and are stored in constant amount of bytes.

Strings have no such limits. Other than memory, which is rarely an issue.

Euphoric
  • 12,645
  • 1
  • 30
  • 44
  • I think this is missing the point; for complexity analysis it's usually wrong to reason from fixed, finite limits like this, because otherwise e.g. the square-and-multiply algorithm takes O(1) time because there are only finitely many possible inputs. For a more subtle example, the worst case time for bubble sort is when the array is like `[5, 4, 3, 2, 1]`, but you cannot construct such a worst-case of arbitrary length `n` if your numbers must be bounded by a constant. – kaya3 Feb 11 '20 at 12:22