If you use a hashmap (or dict in python) and add a new key /increment key count for every letter found O(n) or O(1)? I ask because the max size of the hashmap will be for 26 keys
the alternative solution is to initialize an array of zeroes of length 26 and increment the index corresponding to a letter if it occurs (increment arr[0] if a exists for example). from my understanding, such a solution would require O(1) extra space.
I guess the overarching question is if an input can only have x unique character input , then is the extra space considered O(1) ?
The N
in O(N)
is the number of elements in your array. Since your space requirement will be the same whether you pass in 100 elements or 100,000,000, the space requirement is O(1)
: it doesn't depend on input size.
Technically, python integers can grow indefinitely. This means that your space requirement is actually something like O(log(N))
since O(log_base_256(N)) = O(log(N) / log(256)) = O(log(N))
. Most other languages have a true O(1)
requirement because they cap the size of an integer, be it at 32 or 64 bits. For all practical purposes, you can cap the size of an integer at a value large enough to describe all the available memory, and call it O(1)
.