Initializing an Array in O(1) Time

Initializing an array usually takes O(n) time, when we spend O(n) time setting bits of data at a specific location in memory to 0. Given that our machine memory can contain junk data, how do we build a data structure(an array) that initializes in O(1) time, has O(1) updates, O(1) queries, and O(n) space (worst case analysis here). We can assume that each array entry fits in k bits, and that n fits in one machine word.

We use a total of three arrays to accomplish this. We do not set any of these arrays to 0 initially. In the first array, we store our data entries, each of k bits. In the second, we store the position indices of those that we have visited, in order (so that if we see an element here, we know that the element in that position in the first array is correct). At this point in time, if we also maintain a separate integer m, to count the number of unique indices we have visited already, we can solve this array construction problem in O(n) updates, by iterating through the second array from positions 0 to m-1, so that when we are queried, we can figure out if the element at the position index is correct by linear searching through the second array.

To avoid this problem of having to do a linear search, if we wish to figure out if position p has been visited before, we store it’s position m_p in a third array at position p. Now, if we need to update or query the array at position p, we check index p in our third array, then check that value m_p is less than our current second array size m. If it is indeed less than m, then we check if the value at the index m_p in array two is indeed p. If it is, we know that the value at index p in the first array is correct, and we can update accordingly. If it is not inside, we can either output 0 in the case of a query, or in the case of an update, simply increment m, and update the appropriate values in the first, second, and third arrays.

Leave a comment