0
votes

I've read STL deque accessing by index is O(1)? and how does random access of an element in deque gives constant time complexity? and it still doesn't seem clear to me why O(1) random access is guaranteed.

I understand a deque in STL is implemented as an array of pointers to contiguous fixed size chunks. So I understand looping over a fixed size chunk is O(1) because it is independent of the size of the deque. But to find which chunk to loop over, we need to loop over an array of pointers, which I don't believe is an O(1) operation because the array of pointers is proportional to the size of the deque?

For example, if we have an n sized deque and the fixed chunk size is say, m, our array of pointers would be size ceiling(n/m), which is O(n)? Am I misunderstanding something?

1

1 Answers

0
votes

You aren't looping over the "array" of pointers. Finding the pointer is a constant time operation because you can find the chunk by adding a constant to the pointer to the first index in the pointer array.

For example, using your notation, if you have an n-sized deque, with m-sized chunks, to find the j-th element, you'd need to find the pointer to the chunk that contains the j-th element, as you said. But this doesn't involve looping over the "array" of pointers. In this case the constant that needs to be added is j/m.