79287883

Date: 2024-12-17 12:37:49
Score: 1
Natty:
Report link

No, that is not how HashMaps works.

Why O(1) Space Complexity?

Remember: Space complexity is extra-space(thus don't include input space) your algorithm needs depending on the input size.

HashMap<Character, Integer> here has fixed size containing only 26 keys representing each Character(1 byte), and 26 values corresponding to each key (which can be a 4 byte integer thus can store values upto 2 Billion).

Irrespective of your input string size, you only need this constant space of HashMap to keep count of characters. Suppose if your string becomes significantly large say in trillions, then you can just change the value type of HashMap to Long(16 Byte) to hold even much bigger values for each character, again still your extra space is independent of input size and constant, thus has Space Complexity of O(1).

Reasons:
  • Long answer (-0.5):
  • No code block (0.5):
  • Contains question mark (0.5):
  • Low reputation (0.5):
Posted by: amangupta