-1

Are storing strings O(1) space? I am really confused about this since a mix of people saying its O(1) and O(n) at the same time.... Could someone help me on this one? I really need it for practicing for my interviews. Thank you!!

Berthur
  • 4,300
  • 2
  • 14
  • 28
wiZzz
  • 67
  • 1
  • 4
  • 1
    [Space complexity](https://en.wikipedia.org/wiki/Space_complexity) is about the memory used to perform a computation. It's not about the memory used to store a variable. – Enigmativity Nov 14 '21 at 05:27
  • 2
    (I used to work on the Chakra JS engine). Given that JS is a very, very high-level language that deliberately and intentionally hides internal implementation details, what you're asking cannot be answered definitively as it simply isn't in the spec, and JS implementations are free to do what they like. – Dai Nov 14 '21 at 05:28
  • "I really need it for practicing for my interviews" - only if you're interviewing with potential employers that tend to ask objectively bad and unclear technical questions and want an immediate answer without any pushback or clarification-questions from you - in which case why work for a company like that? – Dai Nov 14 '21 at 05:29
  • It depends if you know something about the strings ahead of time. A string of 1 millions characters will take a million bytes (or more, depending on encoding). For an arbitrary string of size *n*, you clearly need O(*n*) space, but on the other hand if there is a constant maximum size that you know all the strings you're interested in respect, then you could argue it's O(1) for each string. So really, the question is underspecified. – joanis Nov 15 '21 at 21:04

1 Answers1

-2

O(1) would make sense only for complexity and not space since the size of the memory allocated for a string depends on how big it is.

As for complexity:

Depending on how the language implements it (stack or heap) it would be O(1) for stack or non-deterministic for heap, because heap allocation is handled by the OS (but as a rule of thumb, its generally O(1) if the strings are not huge).

O(n) would be for space:

When you store a string, basically what you are doing is storing an array of characters.

This would be the size of the string, since it grows linearly with the size of the string (Every character = 1 byte in a ASCII(8-bit) string).

0xd34dc0de
  • 493
  • 4
  • 10
  • 1
    The ECMAScript specification does not state anything about how `string` values are represented internally (though ECMAScript does require Unicode compatibility). – Dai Nov 14 '21 at 05:34
  • I didn't see the mention of JavaScript in the title. Which resulted in a more generic answer. However you are right. It's best not to assume how it is implemented. – 0xd34dc0de Nov 14 '21 at 05:38